繁体   English   中英

如何在Rails中使用属于自己的模型进行查询

[英]How to Query Using a Model that Belongs To Itself in Rails

我正在使用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'

我真的很感谢您的帮助。

您可以使用2个查询来完成

admin_ids = User.where(:is_admin => true).pluck(:id)
@users = User.where(:created_by_id => admin_ids)

我这样做是因为

  • 很多时候,2个简单查询比1个复杂连接查询快
  • 可读易懂

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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