简体   繁体   中英

Has many through relationship in rails

I am using facebook api to fetch users from fb.

I want to store the users in my model User

I am using has many through relationship to store users

User model relationship I have in my user model.

has_many :friends, :through => :user_friends, :class_name => "User", :foreign_key => "friend_id"

User friends model intermediate table to fetch friends of a user.

belongs_to :user
belongs_to :user, :foreign_key => "friend_id"

User friends has user_id and friend_id columns I added those in migration.

I get an error when I use .friends on a user object.

ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :user_friends in model User

can anyone help with this? Thanks in advance.

You need to check Self-Referential Association . Apparently you are missing some concepts. You can not add 2 associations with the same name in a single model, (only one of them will respond).

You should add has_many :user_friends , but you will still be missing the other side of the association, check this example:


# user.rb
has_many :user_friends
has_many :friends, :through => :user_friends
has_many :inverse_friendships, :class_name => "UserFriend", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user

# user_friends.rb
belongs_to :user
belongs_to :friend, :class_name => "User"

has_many :through行之前添加has_many :user_friends

Try This:

User Model:

has_many :user_friends
has_many :friends, :through => :user_friends, :class_name => "User", :foreign_key => "friend_id"

Friends Model:

  has_many :user_friends
  has_many :users, through: :user_friends

User Friends Model

  belongs_to :user
  belongs_to :friend, :foreign_key => "friend_id"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM