Advertisement
Guest User

Untitled

a guest
Oct 24th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. User.first.friends
  2.  
  3. User.first.friendships
  4.  
  5. +---------+-----------+
  6. | user_id | friend_id |
  7. +---------+-----------+
  8. | 1 | 2 |
  9. | 1 | 3 |
  10. +---------+-----------+
  11.  
  12. create_table "friendships", id: false, force: :cascade do |t|
  13. t.integer "user_id"
  14. t.integer "friend_id"
  15. end
  16.  
  17. create_table "users", force: :cascade do |t|
  18. t.string "name"
  19. t.datetime "created_at", null: false
  20. t.datetime "updated_at", null: false
  21. end
  22.  
  23. class Friendship < ApplicationRecord
  24. belongs_to :user, foreign_key: "user_id", class_name: "User"
  25. belongs_to :friend, foreign_key: "friend_id", class_name: "User"
  26. end
  27.  
  28. class User < ApplicationRecord
  29. has_many :friendships, foreign_key: "user_id", class_name: "Friendship"
  30. has_many :friends, through: :friendships
  31. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement