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",
开发者_StackOverflow社区 :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?
Drop the :finder_sql
and refer to this:
http://guides.rubyonrails.org/association_basics.html#self-joins
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 %{}
精彩评论