Rails scope for values โ€‹โ€‹only between two dates

I like to have a scope in Rails to select only values โ€‹โ€‹between two dates.

Here is my example:

I have a model with the attribute 'startDate' and 'endDate'. Both are of type date

Now I want to select every entry from today, which is between these two dates.

I did scope as follows.

class Product < ActiveRecord::Base scope :activeDate, -> { where("? >= ? AND ? <= ?", Time.now.to_date, :saleStartDate, Time.now.to_date, :salesEndDate)} 

In the controller:

 @products = Product.activeDate 

Unfortunately this will not work. Are there any rails (more beautiful) to get all the records?

Many thanks.

+7
scope ruby-on-rails
source share
1 answer

You can do it:

 scope :activeDate, -> { where("? BETWEEN startDate AND endDate", Time.now.to_date)} 

Since you use a greater or equal value AND less than or equal, you can use the equivalent SQL function "BETWEEN".

You do not need to convert time to date, you can directly call Date.today:

 scope :activeDate, -> { where("? BETWEEN startDate AND endDate", Date.today)} 

You can improve your scope by following these steps:

 scope :activeAtDate, lambda{ |date = Date.today| where("? BETWEEN startDate AND endDate", date) } 

And use it as follows:

 Product.activeAtDate() #=> use the Date.today Product.activeAtDate(1.week.ago.to_date) #=> use Today - minus 7 days 
+16
source share

All Articles