ruby on rails - How to use join and group to get highest amount of specific records -


models: person.rb

# table name: people # #  id                         :integer          not null, primary key #  pesel                      :string           not null #  first_name                 :string           not null #  last_name                  :string           not null 

work_schedule.rb

# table name: work_schedules # #  id          :integer          not null, primary key #  start_time  :time             not null #  end_time    :time             not null #  day_of_week :string           not null #  person_id   :integer          not null 

associations: person.rb

has_many :work_schedules, dependent: :destroy 

work_schedule.rb

belongs_to :person 

what try:

@day_most_work = workschedule.includes(:person).group('work_schedules.id, work_schedules.day_of_week').order('count(work_schedules.day_of_week) desc').first.day_of_week 

issue: don't have idea how create correct query day_of_week people associated. e.g. 23 people work on monday, 54 people work on friday. query should return friday(more employeers on monday). think query incorrect because if change desc asc return same day(in case monday). working day cannot least working day in same time. query create in action of controller.


Comments