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:
- Rails auto saves the associations.You need to call
save
only if the user model is new. - 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
精彩评论