Rails scope for values only between two dates

2020-08-21 02:11发布

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条回答
啃猪蹄的小仙女
2楼-- · 2020-08-21 02:19

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
查看更多
登录 后发表回答