My controller has the following query :
# 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)
I also have this in the controller :
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
The query's result in psql is as follows :
count | cities
-------+---------------
409 | NYC
244 | SF
156 | LA
My end goal is to display the above result as a hash, having as keys the cities, and the count as values..
In the view I've tried doing :
<td><%= Hash[@data_count_by_city.map{ |r| [r.cities,r.count] }] %></td>
But all I get is an empty hash.. What am I missing?
It appears the relation was returning no results (empty relation: #<ActiveRecord::Relation []>
). OP find out he was running the query on Production and the code on a different environment.
Other than that, the code seems to work as expected, as long as @data_count_by_city
stores an array-like structure with both cities
and count
. On that note, I think
.group('display_name').count
shouldn't need the .select('COUNT(*) AS count, "display_name" AS cities')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.