开发者

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

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?开发者_StackOverflow中文版

Yours, Joern.


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜