Ruby-on-rails Rails - 尝试从日期范围查询...从今天开始的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2716886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails - Trying to query from a date range...everything from today
提问by ChrisWesAllen
I'm trying to figure the best way to query a date range from rails...I looked around on Google but am unsure about how to use this syntax.
我试图找出从 rails 查询日期范围的最佳方法......我在谷歌上环顾四周,但不确定如何使用这种语法。
I have a Model that has various events and I like to add to my find condition a caveat that should only show events where the field :st_date is today or later, in effect only show me data that is current, nothing that happened before today.
我有一个包含各种事件的模型,我喜欢在我的查找条件中添加一个警告,该警告应该只显示字段 :st_date 是今天或之后的事件,实际上只显示当前的数据,在今天之前没有发生任何事情。
I ran into a problem because I have no end date to stop the query, I want to query everything from today to next month.
我遇到了一个问题,因为我没有结束日期来停止查询,我想查询从今天到下个月的所有内容。
I was thinking something like
我在想像
@events = Event.find(:all, :conditions => ["start_date between ? and ?",
date.Today, date.next_month.beginning_of_month])
but I get the error undefined local variable or method `date'......
但我收到错误未定义的局部变量或方法`date'......
Do I need do anything particular to use the Date class? Or is there something wrong with my query syntax? I would really appreciate any help.
我需要做什么特别的事情来使用 Date 类吗?还是我的查询语法有问题?我真的很感激任何帮助。
回答by brad
You want Date.today, not date.today. There's nothing wrong with what you're doing, you're just not referencing the date class properly
你想要 Date.today,而不是 date.today。你在做什么没有错,你只是没有正确引用日期类
Furthermore it would be Date.today.next_month.beginning_of_month
此外,它将是 Date.today.next_month.beginning_of_month
回答by mrwade
I would take it a step further and define a scope in your model for reuse.
我会更进一步,在您的模型中定义一个范围以供重用。
# rails 3 example:
# app/models/event.rb
scope :upcoming, lambda {
where("start_date between ? and ?", Date.today, Date.today.next_month.beginning_of_month)
}
# app/controllers/some_controller.rb
@events = Event.upcoming
There is also a great Railscasts episode on scopes in Rails 3:
http://railscasts.com/episodes/202-active-record-queries-in-rails-3
关于 Rails 3 中的作用域,还有一个很棒的 Railscasts 插曲:http:
//railscasts.com/episodes/202-active-record-queries-in-rails-3
回答by Sohan
Event.where(:start_date => Date.today..Date.today.next_month.beginning_of_month)also works great.
Event.where(:start_date => Date.today..Date.today.next_month.beginning_of_month)也很好用。

