[英]How to Query Using a Model that Belongs To Itself in Rails
I'm using Rails 3.2. 我正在使用Rails 3.2。 I have a setup similar to the following: 我有一个类似于以下内容的设置:
class User < ActiveRecord::Base
attr_accessible :is_admin
belongs_to :created_by, :foreign_key => :created_by_id, :class_name => 'User'
end
This works if not using ActiveRecord query, just like the following: 如果不使用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'
I would really be grateful for any help. 我真的很感谢您的帮助。
You could do it using 2 queries 您可以使用2个查询来完成
admin_ids = User.where(:is_admin => true).pluck(:id)
@users = User.where(:created_by_id => admin_ids)
I'd do this because 我这样做是因为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.