简体   繁体   中英

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

I'm using 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:

#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

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

I'd do this because

  • A lot of times, 2 simple queries are faster than 1 complex join query
  • Readable & easy to understand

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