Rails应用程序中的Heroku PostgreSQL GROUP_BY错误

时间:2011-01-04 22:12:44

标签: postgresql ruby-on-rails-3 heroku

我有一个在开发中运行良好的rails应用程序(SQLite),但是当我通过Heroku部署它时会抛出很多错误,Heroku使用我收集的PostgreSQL。

返回错误消息:

        ActionView::Template::Error (PGError: ERROR:  
column "practices.id" must appear in the GROUP BY clause or be used in an aggregate function: 
SELECT "practices".* 
FROM "practices" WHERE ("practices".activity_id = 1) 
AND ("practices"."created_at" BETWEEN '2011-01-01' AND '2011-01-31') 
GROUP BY DATE(created_at) ORDER BY created_at DESC):

当我打电话给以下内容时会抛出这个:

def month_days_not_practiced(date = Date.today)
   p = practices.where(:created_at => date.at_beginning_of_month..date.at_end_of_month).group("DATE(created_at)").to_a.count
   days_in_month(date.year, date.month) - p
end

我真的希望保持代码清洁,以便它适用于开发和生产数据库......任何人都可以解决这些问题吗?

我试过这个:

def month_days_not_practiced(date = Date.today)
   p = practices.where(:created_at => date.at_beginning_of_month..date.at_end_of_month).group("practices.id, DATE(created_at)").to_a.count
   days_in_month(date.year, date.month) - p
end

无济于事......

TIA。

3 个答案:

答案 0 :(得分:5)

Practice.group(Practice.col_list)



def self.col_list
  Practice.column_names.collect {|c| "practices.#{c}"}.join(",")
end

答案 1 :(得分:4)

您需要按所有分组选择列表中的列,所以

.group("practices.id, practices.foo, practices.bar, ..., DATE(created_at)")

您只想按id分组的想法是合理的(假设id是主键),但PostgreSQL只支持9.1版本。

答案 2 :(得分:0)

Practice.joins(:foobar).group_all

def self.group_all
  group(group_all_columns)
end

def self.group_all_columns
  @group_all_columns ||= column_names.collect {|c| "#{table_name}.#{c}"}.join(",")
end