我的控制器有以下查询:
# reports_between_two_dates is already defined
@data_count_by_city = reports_between_two_dates
.joins('JOIN "places" ON "places"."id"="reported_regs"."reported_place_id" JOIN "cities" ON "places"."city_id" = "cities"."id" ')
.where('"reported_regs"."reported_place_id" IN (SELECT "places"."id" FROM "places") AND "places"."city_id" IN (SELECT "cities"."id" FROM "cities")')
.group('"display_name"')
.select('COUNT(*) AS count, "display_name" AS cities')
.order('count DESC')
.limit(3)
我在控制器中也有这个:
respond_to do |format|
format.js {
render json: {
html: render_to_string(
partial: 'data_stats',
locals: {
data_count_by_city: @data_count_by_city
}) } }
format.html
end
psql中的查询结果如下:
count | cities
-------+---------------
409 | NYC
244 | SF
156 | LA
我的最终目标是将上述结果显示为哈希,将城市作为键,将计数作为值。
在我尝试过的视图中:
<td><%= Hash[@data_count_by_city.map{ |r| [r.cities,r.count] }] %></td>
但我得到的只是一个空哈希.. 我错过了什么?
答案 0 :(得分:1)
似乎关系没有返回任何结果(空关系:#<ActiveRecord::Relation []>
)。 OP发现他正在运行生产查询和不同环境下的代码。
除此之外,代码似乎按预期工作,只要@data_count_by_city
存储类似于数组的结构cities
和count
。在那方面,我认为
.group('display_name').count
不应该需要.select('COUNT(*) AS count, "display_name" AS cities')