简体   繁体   English

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

[英]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 我这样做是因为

  • A lot of times, 2 simple queries are faster than 1 complex join query 很多时候,2个简单查询比1个复杂连接查询快
  • Readable & easy to understand 可读易懂

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

相关问题 如何为属于自身的rails模型编写迁移 - How to write a migration for a rails model that belongs_to itself Rails 模型,属于很多 - Rails Model, belongs to many Rails-y查询具有belongs_to关联的模型的方法 - Rails-y way to query a model with a belongs_to association Rails 3 - 与自身具有一对一关系的 model - 我需要belongs_to - Rails 3 - A model with a one to one relationship to itself - do I need belongs_to 在 Rails 中,如何验证属于另一个 model 的 model 上的属性? - In Rails, how do I validate a property on a model that belongs to another model? 在Rails中,如何将一个模型两次连接到一个多态属于的另一个模型? - In Rails, how to connect a model twice to another model that it polymorphically belongs_to? 当一个模型属于 Rails 中的另一个模型时,如何列出它? - How can I list a model when it belongs to a another model in rails? Rails 4-如何在同一模型上两次使用“ belongs_to”(一次使用“ foreign_key”)? - Rails 4 - how to use “belongs_to” on the same model twice (once with using “foreign_key”)? Rails,将has_and_belongs_to_many与抽象模型一起使用 - Rails, using has_and_belongs_to_many with abstract Model 在多模型视图导轨中使用Has_and_belongs_to_many关联 - Using Has_and_belongs_to_many association in multi model view rails
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM