On Dec 25, 2006, at 3:39 AM, Chad A. wrote:
select members.* from members, friends where friends.member_id =
53930410
Ignore the logic, the point is, self.id keeps translating to some
crazy number like 53930410 instead of what it should be, 2.
Any ideas why?
Sure, you are getting the wrong self. Try:
has_many :friends, :class_name => “Member”, :finder_sql => ‘SELECT
members.* FROM members, friends WHERE friends.member_id = #{self.id}’
Note the change from "-quotes to '-quotes. You want the #{self.id}
to be evalulated later when the SQL is needed, not while you’re
defining the :finder_sql. (That is, when self is an instance of
Member not the class itself.)
You could also have escaped the interpolation “SELECT … #{self.id}”
Do you really need :finder_sql in this case? If a member can really
have more than one friend, wouldn’t you need another table to hold
the relationship (i.e., the friendships table)?
class Member < ActiveRecord::Base
has_many :friendships, :dependent => :destroy
has_many :friends, :through => :friendships
end
class Friendship < ActiveRecord::Base
belongs_to :member
belongs_to :friend, :class => ‘Member’, :foreign_key => :friend_id
end
-Rob
Rob B. http://agileconsultingllc.com
[email protected]