Search code examples
ruby-on-railsruby-on-rails-3postgresqlactiverecordrails-postgresql

Grouping a timestamp field by date in Ruby On Rails / PostgreSQL


I am trying to convert the following bit of code to work with PostgreSQL.

After doing some digging around I realized that PostgreSQL is much stricter (in a good way) with the GROUP BY than MySQL but for the life of me I cannot figure out how to rewrite this statement to satisfy Postgres.

def show
  show! do
    @recent_tasks = resource.jobs.group(:task).order(:created_at).limit(5)
  end
end

PG::Error: ERROR:  column "jobs.created_at" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: ...ND "jobs"."project_id" = 1 GROUP BY task ORDER BY created_at...
                                                         ^
: SELECT  COUNT(*) AS count_all, task AS task FROM "jobs"  WHERE "jobs"."deleted_at" IS NULL AND "jobs"."project_id" = 1 GROUP BY task ORDER BY created_at DESC, created_at LIMIT 5

Solution

  • You cannot use column in order which is not in group by.
    You can do something like

    @recent_tasks = resource.jobs.group(:task, :created_at).order(:created_at).limit(5)
    

    but it will change result

    You can also

    @recent_tasks = resource.jobs.group(:task).order(:task).limit(5)
    

    or

    @recent_tasks = resource.jobs.group(:task).order('count(*) desc').limit(5)