【问题标题】:How do I find all the records that have a specific value of an association?如何找到具有特定关联值的所有记录?
【发布时间】:2019-05-03 18:06:27
【问题描述】:

我有一个property 模型belongs_to :property_type

我想在我的 Property 模型上创建一个范围,以查找特定 property_type 的所有记录。

如何找到所有带有property_type.name == "Residential"property 记录?

我尝试了以下方法:

> Property.where('property_type.name = "Residential"').count
   (5.4ms)  SELECT COUNT(*) FROM "properties" WHERE (property_type.name = "Residential")
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property_type"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (property_type.name...

还有这个:

> Property.where('property_types.name = "Residential"').count
   (1.8ms)  SELECT COUNT(*) FROM "properties" WHERE (property_types.name = "Residential")
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property_types"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (property_types.nam...

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案1】:

    您可以使用连接来过滤 property_type

    Property.joins(:property_type).where(property_types: {name: "Residential"}).count
    

    Property.joins(:property_type).where("property_types.name = ?", "Residential").count
    

    【讨论】:

    • 哪种方法更好?
    • 首先我想说,它更干净。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多