Search code examples
ruby-on-railsloopsrangeeachsegment

Rails get equal segments in between a date range


I have a product model and orders associated to the product. I wanted to analyze all orders from creation of product to current time. I was thinking to optimize, I would take products created at day, and current time as start and end points. The next step would be to automatically pull 10 equally spaced times between start and current time and place them in an array. For each one of these dates, query orders for the 10 dates provided.

Question is, is this the best approach to analyzing order data / performance on the query? If so, how do you pull the 10 dates in between the created at and current time range in Rails.

I have the following pseudocode --

Products.where(event_id: event)[Products.where(event_id: event).first.created_at.to_i..Time.now.to_i)].each_slide(10) do |p|
  # Loop through orders of the 10 pulled days
  Orders.where(product_id: p.id).each do |o|
    # Add products to one of the 10 pulled days
  end
end

Solution

  • Example Pseudocode:

    1st Getting the last Product's created_at value

    require 'date'
    prod_date = Products.where(event_id: event).last.created_at
    prod_date = prod_date.to_time.strftime("%Y-%m-%d %H:%M:%S")
    

    2nd Getting last 10 records in products table based on prod_date & date_today.

    date_today = DateTime.now.strftime("%Y-%m-%d %H:%M:%S")
    Products.where('event_id ? AND (created_at BETWEEN ? AND ?)',  event, prod_date, date_today).limit(10)
    

    You can also arrange it if you want by adding e.g. .order("created_at DESC")

    3rd Start to iterate with you orders data from the result above.

    Orders.where(product_id: p.id).each do |o|
       # Add products to one of the 10 pulled days
    end
    

    ====================================

    I understand want you plan to do. Honestly I haven't tried that. But, my idea for that is, for ex. you have 10 data & you want to get 3 equally spaced values.

    Why not try to iterate it by 3 (but get the first value).

    Imagine this is your data: 1 2 3 4 5 6 7 8 9 10
    
    get the first = 1
    iterate the next by (3) = 4, 7, 10
    Result = 1, 4, 7, 10
    

    You may need to get the first & last data, depends on how many

    3 equally spaced values

    you want to get from total result count.