In my app I can add offers and give them a start and end date, the offers are displayed as partials. How can I go about only displaying them if the start date is todays date or earlier and the end date has not yet been reached?
So far I have:
offer partial
<% if offer.date_from > Date.today && offer.date_to < Date.today %>
开发者_如何学JAVA <div class="offer_partial">
<div class="offer_title">
<%= offer.title %>
</div>
<div class="offer_body">
<%= offer.body %>
</div>
</div>
<% end %>
But this gives a undefined method `>' for nil:NilClass error.
Is it even ok to do these kind of checks in the view?
Thanks very much for any help!
To answer your second question first, no, you should build a collection of the Offer models through a query in the controller, thereby leaving the view to just iterate through that collection and render the HTML.
Also, the if block doesn't do what you want it to. You said "Today's date or earlier", but you're checking for today's date or later. It seems that you've inverted the logic.
The error you're getting means that date_from is nil. Are you validating those fields or are they allowed to have a nil value?
This is how I would set that collection up:
class Offer < AR::Base
scope :end_date_not_reached, where("date_from <= ?", Date.today).where("date_to > ?", Date.today)
end
In the controller:
@offers_in_progress = Offer.end_date_not_reached
In the view:
<% @offers_in_progress.each do |offer| %>
<!-- stuff here -->
<% end %>
Hope this helps.
精彩评论