简体   繁体   中英

Self-referencing has_many, :through

Here's my User model:

class User < ActiveRecord::Base

  has_many :friends, :class_name => 'Friendship', :dependent => :destroy

end

Here's my Friendship model:

class Friendship < ActiveRecord::Base

  belongs_to :user
  belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id'

  set_table_name :users_users
end

Now, I have a boolean attribute in the User model called *is_awesome*.

When I try to run this query:

User.find(1).friends.find(:all, :include => :users, :conditions => {:is_awesome => false})

I get the following error:

ActiveRecord::StatementInvalid: Mysql::Error: 
Unknown column 'users_users.is_awesome' in 'where clause': 
SELECT * FROM `users_users` 
WHERE (`users_users`.user_id = 1 AND (`users_users`.`is_awesome` = 0))

Any idea what's going on?

You have to change:condition to refer to user table, it should looks something like this:

User.find(1).friends.find(:all, :include => :users, :conditions => "users.is_awesome IS FALSE")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM