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.
You can do this:
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:
You could improve your scope by doing this:
And use it like this: