Search code examples
ruby-on-railsdynamicgroup-byresolution

Rails: groupdate GEM change group resolution dynamic on parameter


Is there a way to use the groupdate gem with a dynamic parameter for data resolution?

Normally you can use

User.group_by_day(:created_at).count

or

User.group_by_week(:created_at).count

But I want to use the day/week option by parameter to change the charts. So I need something like

User.group_by_groupdate(:created_at, resolution: params[:resolution]).count

Where params[:resolution] can be "day", "week", "month", "year", instead of doing something like this:

case params[:resolution]
when "day"
User.group_by_day(:created_at).count
when "week"
User.group_by_week(:created_at).count
end

Solution

  • As stated in the docs, you can do this

    User.group_by_period(params[:resolution], :created_at, permit: %w[day week month year]).count
    

    In permit option you can pass available periods. When you pass something else, ArgumentError will be raised.