User has_many :users, :through => :friends - how?

*爱你&永不变心* 提交于 2019-12-06 14:28:02

问题


This is my code:

class Friend < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"
end

class User < ActiveRecord::Base
  #...
  has_many :friends
  has_many :users, :through => :friends
  #...
end

When I now start adding users by...

user.users << user2
user.save

Only the user_id of friend is filled, friend_id is null.

Any help?

Yours, Joern.


回答1:


You need to add the :source attribute to your has_many through association.

class User < ActiveRecord::Base
 has_many :friends
 has_many :users, :source => :friend, :through => :friends
end

Now the following calls will work.

u1.users << u2    
u.friends.last
# will print #<Friend id: 1, user_id: 1, friend_id: 4>

Notes:

  1. Rails auto saves the associations.You need to call save only if the user model is new.
  2. You probably should rename the association to something more explicit. E.g: friend_users etc.



回答2:


Try: Railscasts - Self-Referential Associations. Generally has very good tutorials on all topics listed.




回答3:


I think you need delete the belongs_to :user in your Friend model



来源:https://stackoverflow.com/questions/2404246/user-has-many-users-through-friends-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!