views:

26

answers:

2

Hi there,

I want to do a model class which associates to itself on Rails. Basically, a user has friends, which are also users. I typed the following inside a User model class:

  has_many :friends, 
    :class_name => "User", 
    :foreign_key => :user_id, 
    :finder_sql => %{SELECT users.*
      FROM
        users INNER JOIN friends
          ON (users.id = friends.user_id OR users.id = friends.friend_id)
      WHERE users.id <> #{id}}

But the funny fact is that it seems that this finder_sql is called twice whenever I type User.first.friends on irb. Why?

A: 

Drop the :finder_sql and refer to this:

http://guides.rubyonrails.org/association_basics.html#self-joins

fig
The problem is that I need a 'friends' table, since a user can have multiple friends, and not necessarily in a hierarchical fashion like in the example.Actually I think it should be has_and_belongs_to_many, but I don't want to specify roles for this relationship (e.g. it doesn't matter where in the friendship end the User is). So I would like to specify a join clause that depicts this requirement. Any thoughts?
Thiago
A: 

I just read this post:

http://railsblaster.wordpress.com/2007/08/27/has_many-finder_sql/

I should have used single quotes to embrace the finder_sql, instead of %{}

Thiago