所以我在这里遇到了一个小问题。基本上我有两个表 - restaurants
和 inspections
(restaurant
模型 has_many :inspections
。我需要拉一个列表在检查中获得特定分数(在本例中为 70)的餐厅的数量。我们的想法是获取每家餐厅的所有检查。
如果我在控制台中运行以下命令...
places = Restaurant.joins(:inspections).where("zip = '78741' AND score = 70").select("name, ST_AsGeoJSON(the_geom) as gj")
...我按预期获得了餐厅列表。它返回名称和 geojson 几何图形。完美的。我怎么知道在 places
上迭代而不遇到整个 1 + N 问题。我尝试使用 includes
但这删除了编写我自己的 select
方法的能力。有什么想法吗?
来 self 的模型
InspectionModel
belongs_to :restaurant, foreign_key: :facility_id
RestaurantModel
has_many :inspections, foreign_key: :facility_id, primary_key: :facility_id
来 self 的数据库:
psql (9.3.3)
Type "help" for help.
maple_dev=# \d+ inspections
Table "public.inspections"
Column | Type | Modifiers | Storage | Stats target | Description
-------------+-------------------+--------------+----------+--------------+-------------
date | date | | plain | |
score | integer | | plain | |
facility_id | character varying | | extended | |
description | character varying | | extended | |
id | integer | not null ... | plain | |
Indexes:
"inspections_pkey" PRIMARY KEY, btree (id)
"index_inspections_on_facility_id" btree (facility_id)
Has OIDs: no
maple_dev=# \d+ restaurants
Table "public.restaurants"
Column | Type | Modifiers | Storage | Stats target | Description
-------------+-------------------+-----------+----------+--------------+-------------
facility_id | character varying | | extended | |
name | character varying | | extended | |
zip | character(5) | | extended | |
address | character varying | | extended | |
latitude | double precision | | plain | |
longitude | double precision | | plain | |
the_geom | geometry | | main | |
Indexes:
"index_restaurants_on_facility_id" btree (facility_id)
Has OIDs: no
最佳答案
你可以使用 ActiveRecord Association Extensions :
#app/models/restaurant.rb
Class Restaurant < ActiveRecord::Base
has_many :inspections, foreign_key: :facility_id, primary_key: :facility_id do
def score(zip, score)
where("zip = ? AND score = ?", zip, score).select("name, ST_AsGeoJSON(the_geom) as gj")
end
end
end
这将允许您调用:
@location1 = Restaraunt.inspections.score("01456", "70")
@location2 = Restaraunt.inspections.score("15654", "80")
过程
- 将“地点”设置为可变数据——目前,它是手动的
- 使用一种方法调用所有必需的数据以满足您的规范
AR Association Extensions 是 Rails 的一项鲜为人知的功能,基本上允许您定义有关您调用的数据的细节。我不知道我的代码是否能正常工作,但它肯定会为您指明正确的方向
关于ruby-on-rails - ActiveRecord::QueryMethod 'includes' 忽略了我的选择方法。我该如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22122587/