Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top