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.
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.