Rails 范围仅适用于两个日期之间的值 [英] Rails scope for values only between two dates
问题描述
我喜欢在 Rails 中有一个范围,用于仅选择两个日期之间的值.
I like to have a scope in Rails for selecting only values between two dates.
这是我的例子:
我有一个属性为startDate"和endDate"的模型.两者的类型都是 'date'
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)}
在控制器中:
@products = Product.activeDate
不幸的是它不起作用.是否有获取所有条目的轨道(更漂亮)?
Unfortunately it does not work. Is there a rails-way (more beautiful) to get all entries?
非常感谢.
推荐答案
您可以这样做:
scope :activeDate, -> { where("? BETWEEN startDate AND endDate", Time.now.to_date)}
由于您使用的是更大的或等于和较小的或等于,您可以使用等效的 SQL 函数BETWEEN".
Since you are using greater or equal AND lesser or equal, you can use the equivalent SQL function "BETWEEN".
您不需要将时间转换为日期,您可以直接调用Date.today:
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)}
<小时>
您可以通过这样做扩大范围:
scope :activeAtDate, lambda{ |date = Date.today| where("? BETWEEN startDate AND endDate", date) }
像这样使用它:
Product.activeAtDate() #=> use the Date.today
Product.activeAtDate(1.week.ago.to_date) #=> use Today - minus 7 days
这篇关于Rails 范围仅适用于两个日期之间的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!