Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails scope for values only between two dates

I like to have a scope in Rails for selecting only values between two dates.

Here is my example:

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

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

I made a scope looks like this.

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 it does not work. Is there a rails-way (more beautiful) to get all entries?

Thanks a lot.

like image 759
N. Mauchle Avatar asked Sep 06 '13 15:09

N. Mauchle


1 Answers

You can do this:

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

Since you are using greater or equal AND lesser or equal, you can use the equivalent SQL function "BETWEEN".

You don't need to convert the Time to a date,you can directly call the Date.today:

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

You could improve your scope by doing this:

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

And use it like this:

Product.activeAtDate() #=> use the Date.today
Product.activeAtDate(1.week.ago.to_date) #=> use Today - minus 7 days
like image 172
MrYoshiji Avatar answered Oct 01 '22 04:10

MrYoshiji