导轨| PG :: GroupingError

时间:2017-07-17 07:36:23

标签: ruby-on-rails postgresql join

我有汽车和car_cities模型。我想得到至少有一辆车的城市。

协会;

CarCity.joins(:cars).group("cars.car_city_id").having("count(cars.id) > 0")

联接查询;

An ActionView::Template::Error occurred in search#search_city:

PG::GroupingError: ERROR:  column "car_cities.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT “car_cities".* FROM "car_cities” INNER JOIN "cars"…

^
: SELECT “car_cities".* FROM “car_cities” INNER JOIN “cars” ON “cars"."car_city_id” = “car_cities"."id” WHERE "car_cities"."car_country_id” = $1 GROUP BY cars.car_city_id HAVING count(cars.id) > 0

app/views/search/_search_filters.html.erb:88:in `block in _app_views_search__search_filters_html_erb__3215729544581234245_70286113854020'

这适用于我的本地环境。但不是在做生产。

错误;

""

2 个答案:

答案 0 :(得分:1)

如果可能的话,在生产控制台上尝试这个..

CarCity.joins(:cars).group("car_cities.id").having("count(cars.id) > 0")

答案 1 :(得分:1)

你可以试试这个问题吗,

CarCity.joins(:cars).group("car_cities.id").having("count(cars.id) > 0")

按cars.car_city_id和car_cities.id分组,两者都对应相同的记录。而且当使用INNER JOIN与' Car'模型,汽车记录仅在汽车数量超过1的情况下被选中。