I have an Event model which contains a start_date field of type datetime. I have a simple model method that is supposed to let me know if the start_date is already active, or if it’s yet to happen:
def future_event?
self.start_date >= DateTime.now
end
Then in my view, I check which view I need to load (based on whether or not the event is happening right now or the event is still in the future). I’ve tried various things like converting both to Time objects, string formatting, etc… Nothing seems to work, the same view is always rendered. Here’s my view code:
<% if @event.future_event? %>
<%= render "pages/main_container_offline" %>
<%= render "pages/sidebar_offline" %>
<% else %>
<%= render "pages/main_container_online" %>
<%= render "pages/sidebar_live" %>
<% end %>
Any ideas?
Edit:
Here’s the output of @event.start_date : 2012-06-10 10:20:00 UTC
Here’s the output of DateTime.now : 2012-06-10T10:35:30-05:00
As you can see, the formatting is different. I’m not sure if this is an issue or not.
Here’s my controller method which sets @event:
def index
@event = Event.active.order("start_date ASC").first
end
## model
scope :active, lambda {
where("end_date >= ?", DateTime.now)
}
So, I finally figured this out. Basically the problem was that Rails saves everything in the UTC timezone, which would always be different than my time locally (hence the improper rendering). In order to fix this, I had to tell Rails and ActiveRecord to save everything using my timezone, and display everything in my timezone as well. The following changes fixed my problem:
application.rb
model.rb