所以我在这里遇到一些问题。基本上我有两个表 - 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
方法。有什么想法吗?
从我的模特
InspectionModel
belongs_to :restaurant, foreign_key: :facility_id
RestaurantModel
has_many :inspections, foreign_key: :facility_id, primary_key: :facility_id
来自我的数据库:
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
答案 0 :(得分:0)
您可以使用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的一个鲜为人知的功能,基本上允许您定义有关您正在调用的数据的细节。我不知道我的代码是否可以解决方案,但它肯定会指向正确的方向
答案 1 :(得分:0)
事实证明,我需要的方法组合是joins
和preload
。如其他地方所述,使用includes
默认使用select
方法返回所有列。在我的情况下,我需要在我的select
调用中运行PostGIS功能,因此includes
不会工作。以下是工作代码:
restaurant_info = Restaurant.joins(:inspections)
.preload(:inspections)
.select(atts)
.where("#{score_search} AND #{q_where}")
这实际上并没有完全解决问题。创建的新问题是restaurant_info
填充了重复的Restaurant
个对象。通过将DISTINCT
添加到我的select方法(名为atts
的字符串)中,可以轻松解决此问题。感谢所有人的帮助。