Reputation: 434
Quick question.
I have the following within a view
<tbody>
<% @courses.each do |course| %>
<% if course.lec_exam.eql?("LEC")%>
<tr class ="text-center">
<td><%= course.location %></td>
<% if (Time.now > course.begin_time && Time.now < course.end_time)
course.status = 'Taken'
else
course.status ='Open'
end %>
<td><%= course.status %></td>
<td><%= course.begin_time %></td>
<td><%= course.end_time %></td>
<td><%= link_to 'Edit Status', edit_course_path(course) %></td>
</tr>
<% end %>
<% end %>
</tbody>
I tested this and begin_time always equates to true and end_time always equates to false. For reference, my DB stores the columns via the following. If it makes a difference, the values are imported via CSV.
t.time "begin_time"
t.time "end_time"
Some example begin_time and end_time values:
2000-01-01 10:30:00 UTC 2000-01-01 11:20:00 UTC
2000-01-01 11:30:00 UTC 2000-01-01 12:20:00 UTC
So I can see why begin_time equates to true and why end_time equates to false. Why do the values have a date associated with them when they're only stored as times, both in the CSV and DB? In the CSV they're stored as 10:30 AM, 11:20 AM, etc.
Any pointers? Anything obvious I'm missing?
Upvotes: 0
Views: 158
Reputation: 1652
First, you should move your logic to your model. Second, the Rails :time datatype still stores a date into the database (even though it isn't used). We'll have to manually strip the date:
Class Course < ActiveRecord::Base
def status
t = Time.now.utc.strftime("%H%M%S%N")
end_time_f = self.end_time.utc.strftime("%H%M%S%N")
begin_time_f = self.begin_time.utc.strftime("%H%M%S%N")
’if (t >= begin_time_f && (t <= end_time_f)
status = 'Taken'
else
status = 'Open'
end
return status
end
end
Then in your view you can simply call course.status
Upvotes: 1
Reputation: 434
Solved. Utilized answer above, as well as the 'tod' gem, which provides a to_time_of_day method for both Time and DateTime.
def status
t = Time.now.to_time_of_day
bt = self.begin_time.to_time_of_day
et = self.end_time.to_time_of_day
if (t >= bt) && (t<=et)
status = 'Taken'
else
status = 'Open'
end
return status
end
Upvotes: 0