开发者

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

开发者 https://www.devze.com 2022-12-22 02:29 出处:网络
This is my code: class Friend < ActiveRecord::Base belongs_to :user belongs_to :friend, :class_name => \"User\", :foreign_key => \"friend_id\"

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

精彩评论

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

关注公众号