0

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 %>
    <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!

Dave
  • 1,175
  • 2
  • 21
  • 49

1 Answers1

4

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.

Srdjan Pejic
  • 8,152
  • 2
  • 28
  • 24
  • Thanks very much! Thats exactly what I was after. – Dave Sep 28 '11 at 22:03
  • @srdjan-pejic I think you may need to use `lambda` in the scope to ensure the Date that's compared is calculated when the scope is called. Previous experience has taught me you might get some weird results otherwise.`class Offer < AR::Base scope :end_date_not_reached, lambda {{ :conditions => ["date_from <= ? AND date_to > ?", Date.today, Date.today] }} end` – Pete Sep 28 '11 at 22:56
  • Right I think my suggestion is now wrong as off 3.1. Looks like lambda scopes have been deprecated. – Pete Sep 29 '11 at 00:12