How to use group in nested associations

The below query fails:

Timesheet.joins(:time_entries).select(“timesheets.*, sum(time_entries.worktime) as total”).group(“timesheets.start_date”)

The models have the following relations:

Timesheet < AR

has_many :activities, dependent: :destroy, inverse_of: :timesheet

has_many :time_entries, through: :activities

accepts_nested_attributes_for :activities, allow_destroy: true


class Activity < AR

belongs_to :timesheet, inverse_of: :activities

belongs_to :task

has_many :time_entries, order: :workdate, dependent: :destroy, inverse_of: :activity

accepts_nested_attributes_for :time_entries, allow_destroy: true, reject_if: proc { |a| a[:worktime].blank? }


class TimeEntry < AR

belongs_to :activity, :inverse_of => :time_entries


How is it possible to group all the time sheets by their start_date and sum the work time ?

Thank you.

I found the way to do that as follows:

either by defining a scope in the Timesheet model:

scope :all_by_start_date, joins(:time_entries).select(“timesheets.start_date, sum(time_entries.worktime) as total_days”).group(‘timesheets.start_date’)

or the same and full console syntax to check it console:

Timesheet.joins(:time_entries).select(“timesheets.start_date, sum(time_entries.worktime) as total_days”).group(‘timesheets.start_date’)

Hope this helps.