AdamNYC
AdamNYC

Reputation: 20445

Update attribute in has_many through

I have the following relationship:

User has_many :relationships
     has_many :friends, :through => :relationships

Friend has_many :relationships

Relationship belongs_to :user, :friend

Now, I would like to update friends of an user, but also update attribute weight in relationships. How should I go about it?

I tried

Friend
accept_nested_attribute_for :relationships

and

  friend = my_user.friends.first
   #update info
   friend.update_attributes(:info => my_info, :relationship => {:weight => 1})

How should I look up at particular relationship between user and friends before updating its weight attribute?

Upvotes: 0

Views: 196

Answers (1)

boulder
boulder

Reputation: 3266

You need to specify the friend's relationship whose weight you are setting, because as your association states, there are many.

There are more than one way to do that. I would probably do:

friend = my_user.friends.first
relationship = my_user.relationships.where(:friend_id => friend.id).first
relationship.update_attributes(:weight => 1)

Upvotes: 2

Related Questions