Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 find() between now and midnight

I have an event model which has start_at of type datetime. How can I search to find if there is an Event left for today, so start_at between now and midnight.

Thanks

like image 280
ed1t Avatar asked Jan 27 '26 22:01

ed1t


2 Answers

In Rails 3, you can do this now:

Range Conditions

If you’re looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the IN SQL statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:

Client.where(:created_at => (params[:start_date].to_date)..(params[:end_date].to_date))

So in your case it would be:

Event.where(:start_at => (Time.zone.now)..(Time.zone.now.end_of_day))

Just tested and it also works without parentheses around Time.zone.now and Time.zone.now.end_of_day.

(From Rails Guides)

like image 75
Mischa Avatar answered Jan 29 '26 13:01

Mischa


Event.where('start_at >= ? and start_at <= ?', Time.zone.now, Time.zone.now.end_of_day)

You will have to deal with user time zones if you want this to be completely accurate for multiple users.

like image 28
Austin Taylor Avatar answered Jan 29 '26 11:01

Austin Taylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!