13

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.

ChrisWesAllen
  • 4,935
  • 18
  • 58
  • 83

4 Answers4

17

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
  • 31,987
  • 28
  • 102
  • 155
15

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

mrwade
  • 151
  • 4
6

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

Pigueiras
  • 18,778
  • 10
  • 64
  • 87
Sohan
  • 3,757
  • 2
  • 24
  • 24
2

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

Event.by_month(Time.now, :field => "start_date")
Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261