Alex Ermolaev
Alex Ermolaev

Reputation: 311

How to get weekly records on Rails?

I have Payment model with data and amount attributes. Now I need to get all the records for the current week on the page. I want to use some kind of pagination, e.g.: On the first page I get all records for the current week, on the second page - records from the previous week etc.

And on every page I need to get total amount for this week and average amount per day.

So, I have two questions:

Now everything I've done was array with weeks and amounts

def self.count_by_week
    raw_result = group_by_week_and_state.count

    # {['2014-12-01-2014-12-07', 'foo'] => 100, ['2014-12-01-2014-12-07', 'bar'] => 100, '...' => '...'}

    raw_result.each_with_object({}) do |(k, v), result|
       result[k[0]] ||= {}
       result[k[0]][k[1]] = v
    end
  end

  def self.group_by_week_and_state
    group("#{weekday_query(0)} || \'-\' || #{weekday_query(6)}").group('amount')
  end

  # build sql part for day offset of week (0 => mon, 6 => sun)
  def self.weekday_query(offset)
    "to_char(cast(date_trunc(\'week\', created_at) as date) + #{offset}, \'YYYY-MM-DD\')"
  end

Upvotes: 0

Views: 369

Answers (1)

Alfie
Alfie

Reputation: 2784

You could use the groupdate gem to accomplish this.

https://github.com/ankane/groupdate

Once you have successfully grouped your records, it's just too simple to get the sum for each groups.

Upvotes: 1

Related Questions