has_many conversely

I have a very simple association: class User < ActiveRecord::Base   has_and_belongs_to_many :friends,     :class_name=>"User",     :join_table=>"friends_users",     :association_foreign_key=>"friend_id",     :foreign_key=>"user_id"

User.friends - returns my friends. How can i get users who "friended" me? Thanks.

FriendUser.find(:all, :conditions => [‘friend_id = ?’,user.id]).collect{|x|x.user}

so I think you can put that in a model function

def befriended_ones FriendUser.find (:all, :conditions => [‘friend_id = ?’,user.id]).collect{|x|x.user} end

I would like to know if there is a way of doing this just using associations…

Right, Ivor. I knew about this way, and also would like to know if there is a way to do it through associations. And another issue, i have rich join model via has_many :through. And collection's clear (user.groups.clear) method works strange. It just clears collection in memory and doesn't touch join table at all. Even not nullify foreign keys, nothing. Is it expected?

Did you try reversing the habtm relationship manually:     has_and_belongs_to_many :friended,      :class_name => "User"      :join_table => "friends_users",     :association_foreign_key => "user_id",     :foreign_key => "friend_id"

You could build a plugin or function that did both ways, if you use self-relations like this often. Otherwise, I don't know anything built into Rails that does it both ways.

- Hal

Kane, I would appreciate it if you could give this a spin and let me know if it worked. thanks Ivor

It's really simple! How i didn't come to this from the beginning. From the 1st sight i think it should work. P.S fast test shows - it really works.