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

时间:2014-09-08 06:44:23

标签: ruby-on-rails ruby

我使用的是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'

我真的很感激任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用2个查询

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

我这样做是因为

  • 很多时候,2个简单查询比1个复杂连接查询更快
  • 可读&amp;易于理解