我使用的是Rails 3.2。我的设置类似于以下内容:
class User < ActiveRecord::Base
attr_accessible :is_admin
belongs_to :created_by, :foreign_key => :created_by_id, :class_name => 'User'
end
如果不使用ActiveRecord查询,则可以使用,如下所示:
#rails console
User.first.created_by.is_admin
#=> true
#But I want to query like the following, but it doesn't work
User.where(:created_by => {:is_admin => true})
#ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'created_by.is_admin' in 'where clause'...
#This also doesn't work:
User.joins(:created_by).where(:created_by => {:is_admin => true})
#ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'created_by.is_admin' in 'where clause'
我真的很感激任何帮助。
答案 0 :(得分:1)
您可以使用2个查询
来完成admin_ids = User.where(:is_admin => true).pluck(:id)
@users = User.where(:created_by_id => admin_ids)
我这样做是因为