views:

181

answers:

4

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 the Date class? Or is there something wrong with my query syntax? I would really appreciate any help.

+4  A: 

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

brad
Thanks alot, its the smallest things usually....
ChrisWesAllen
A: 

:conditions=>{:start_date => Date.today..Date.today.next_month.beginning_of_month} also works great.

Sohan
A: 

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

Event.by_month(Time.now, :field => "start_date")
Ryan Bigg
A: 

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, 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

mrwade
@mrwade: shouldn't your scope include the lambda{} symbol so that that dates are evaluated at the time of usage, rather then when the class is loaded?
Craig