开发者

Rails - Trying to query from a date range...everything from today [duplicate]

This question already has answers here: Rails ActiveRecord date between (11 answers) Closed 9 years ago.

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.

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.

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'......

Do I need do anything particular to use 开发者_如何学JAVAthe Date class? Or is there something wrong with my query syntax? I would really appreciate any help.


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

Furthermore it would be Date.today.next_month.beginning_of_month


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


Event.where(:start_date => Date.today..Date.today.next_month.beginning_of_month) also works great.


Take a look at my by_star plugin which lets you do things like:

Event.by_month(Time.now, :field => "start_date")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜