Home > Software engineering >  Rails best practice for getting past 10 entries in model
Rails best practice for getting past 10 entries in model

Time:11-05

I want to get the sales from the past 10 weeks. I can do that with this method:

def past_10_sales(yw)
  past_sales = []
  year_week = yw

  10.times do
    sales = Sales.where(year_week: year_week.previous)

    past_sales << sales unless sales.empty?
    year_week = year_week.previous
  end
  past_sales.flatten
end

But now I need this method somewhere else as well and wanted to put it in the sales.rb model, but i don't know what the best practice of this would be or if there is something in Rails that makes this better? It feels wrong calling Sales.where in the sales.rb model...

Edit: year_week is a model with the current year and calendar week. So the current year_week would be 202244. Calling year_week.previous gives me 202243. I'm getting all the sales from a specific calendar week. This works fine btw.

Edit 2: I have a model sales.rb. in this model i save all the sales. it only matters in which calendar week the sales were made, the exact date does not matter so it looks something like this:

create_table "sales" do |t|
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.bigint "year_week_id"
  etc...
end

i also have a model year_week which just saves the year and the calendarweek and the id is like this: yearweek (so 202244). there are methods like def previous that return the previous year_week.

What i now want is all the sales form the past 10 weeks. so i call this:

    sales = Sales.where(year_week: year_week.previous)

    past_sales << sales unless sales.empty?
    year_week = year_week.previous

10 times because this way it gets all the sales in the past 10 weeks but it just doesn't feel right and i was wondering if/what better way there is for this.

CodePudding user response:

If you really have to work with a bigint you can do something like:

starting_week = Time.current.advance(weeks: -10).strftime("%Y%V").to_i
Sale.where(
  year_week: starting_week.. 
)

This uses ISO weeks. Otherwise use %U or %W. See DateTime#strftime. Of course using date_trunc('week', sales.created_at) or the equivilent database function would make this column reduntant unless the week isn't actually the same as the calender week its created.

CodePudding user response:

you can do it in the below way:

def past_10_sales(yw)
  year_week = yw.previous
  past_sales = Sales.where(year_week: (year_week-9..year_week.to_a))
end
  • Related