开发者

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

开发者 https://www.devze.com 2022-12-26 07:44 出处:网络
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:

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 %{}

0

精彩评论

暂无评论...
验证码 换一张
取 消