Thursday, February 16, 2006

HABTM - Self Referential - Checking Whether An Association already exists

I am loving Rails. Today I found a cool way to check whether an association already exists in a habtm relationship

member1=Member.find(1)
member2=Member.find(2)

member1.friends << member2 unless member1.friends.include?(member2)


Pretty cool, eh?

1 Comments:

At 4:55 AM, Blogger Night Crawler said...

Hi, can u provide me with some example as to how can i update an extra attribute like status in the join table - friends_member ?

A friend system is pretty much simple, and normally contains one extra attribute such as status besides user_id, and friend_id.

so the questions is how to put a value into status when adding a friend through member1.friends << another_friend

WILL BE HIGHLY APPRECIATED

 

Post a Comment

<< Home

eXTReMe Tracker