Home > OS >  Rails refactoring long where conditions
Rails refactoring long where conditions

Time:11-18

I don't like passing multiple repeating arguments, it looks a bit ugly.
how can I refactor the following code?

 prev_month_start = Date.today.prev_month.beginning_of_month
 prev_month_end = Date.today.prev_month.end_of_month
    
 contacts = contacts.where('
   persons.actual_delivery_date >= ? AND persons.actual_delivery_date <= ? OR 
   persons.expected_shipment_date >= ? AND persons.expected_shipment_date <= ?', 
   prev_month_start, prev_month_end, 
   prev_month_start, prev_month_end)

CodePudding user response:

You can use a date range (all_month) in cases like these combined with a or condition:

prev_month = Date.today.prev_month.all_month
contacts = contacts
  .where(persons: { actual_delivery_date: prev_month })
  .or(contacts.where(persons: { expected_shipment_date: prev_month }))

CodePudding user response:

You can try something like this with ActiveRecord 5 and above:

contacts.where(actual_delivery_date: prev_month_start..prev_month_end).or(expected_shipment_date: prev_month_start..prev_month_end) 

https://guides.rubyonrails.org/active_record_querying.html#range-conditions

edited based on comments

  • Related