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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With