Problems using an id from a model inside a custom sql query in Rails

Posted by Thiago on Stack Overflow See other posts from Stack Overflow or by Thiago
Published on 2010-04-12T19:46:44Z Indexed on 2010/04/12 20:23 UTC
Read the original article Hit count: 338

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about rails

Related posts about model