如何找到具有特定关联值的所有记录?
How do I find all the records that have a specific value of an association?
我有一个 property
模型 belongs_to :property_type
。
我想在我的 Property
模型上创建一个范围,以查找特定 property_type
的所有记录。
如何找到所有 property
条带 property_type.name == "Residential"
的记录?
我试过以下方法:
> 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...
您可以使用联接来过滤 property_type
Property.joins(:property_type).where(property_types: {name: "Residential"}).count
或
Property.joins(:property_type).where("property_types.name = ?", "Residential").count
我有一个 property
模型 belongs_to :property_type
。
我想在我的 Property
模型上创建一个范围,以查找特定 property_type
的所有记录。
如何找到所有 property
条带 property_type.name == "Residential"
的记录?
我试过以下方法:
> 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...
您可以使用联接来过滤 property_type
Property.joins(:property_type).where(property_types: {name: "Residential"}).count
或
Property.joins(:property_type).where("property_types.name = ?", "Residential").count