【发布时间】:2018-02-17 13:13:00
【问题描述】:
我的控制器有以下查询:
# 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>
但我得到的只是一个空哈希.. 我错过了什么?
【问题讨论】:
-
Ruby 中的查询结果是什么:
@data_count_by_city.inspect? -
那么,你想在erb中渲染一个哈希?
-
@Leito 结果是:#<:relation>
-
没有结果,这就是你得到一个空哈希的原因。所以让我们回到查询,忘记控制器和视图。 SQL中的查询是什么?您在 Rails 服务器的日志中看到的查询是什么?
-
如果您的关联定义正确,则不需要自定义连接字符串。可以包含模型吗?
标签: ruby-on-rails ruby activerecord hash