Rails scope for values only between two dates

纵饮孤独 提交于 2019-12-10 03:20:48

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/18661777/rails-scope-for-values-only-between-two-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!