PSCampbell
PSCampbell

Reputation: 868

each do if not nil - Rails

I've got an invoices model that has a paid boolean attribute. There's an association between accounts and invoices and I'd like to show only unpaid invoices in a view.

I'm using this to show all invoices:

<table class="table">
  <thead>
    <tr>
      <th>Invoice Number</th>
      <th>Invoice Date</th>
      <th>Invoice Total</th>
    </tr>
  </thead>

  <tbody>
    <% @account.invoices.each do |invoice| %>
      <tr>
        <td><%= invoice.id%> </td>
        <td><%= invoice.created_at.time.to_formatted_s(:long)%> Zulu </td>
        <td><%= invoice.total %></td>
      </tr>
    <% end %>
  </tbody>

But I'm unsure how to limit results to where only invoices where paid is nil will be shown. I tried: <% @account.invoices.each do |invoice| unless @account.invoices.paid == 'nil' %>, but hit errors. Obviously I'm getting my syntax wrong. Any advice?

Upvotes: 2

Views: 863

Answers (1)

Radix
Radix

Reputation: 2747

You can use named scope in this case.

Created an unpaid scope in invoices model:

scope :unpaid, -> { where( paid: [nil, false] ) }

And use that in views, like this:

<% @account.invoices.unpaid.each do |invoice| %>

Upvotes: 8

Related Questions