capcode01
capcode01

Reputation: 163

Rails 3 each do ignore nil values

I am building an html table that should include name, rating1, rating2, and rating3. rating 1-3 come from different models than name.

resources :names do
  resource :rat1,:rat2,:rat3
end

Inside of my html table I'd like to include the ratings from within each of these tables but I would like to automatically skip over or ignore tables that are nil. This is because :names may only have a :rat1 and not a :rat2 or :rat3. My view should look something like this.

    <table>
      <thead>Name</thead>
      <thead>Rating 1</thead>
      <thead>Rating 2</thead>
      <thead>Rating 3</thead>
      <% @names.each do |name| %>
        <tr>
          <td><%= name.nametext %></td>
          <td><%= name.rat1.rating %></td>
          <td><%= name.rat2.rating %></td>
          <td><%= name.rat3.rating %></td>
        </tr>
      <% end %>
    </table>

Except that if name.rat1 is nil it will either a.) replace the value with N/A OR b.) it will leave this field blank and move on to the next.

What is the cleanest way to do this?

::UPDATE::

So my issue is that the name.rat1 is nil and the name.rat1.rating is an undefined method of a nil class so both of these options will throw the same undefined method of a nil class error regardless of the || or helper method. At least thats what my current tests are showing. Any other options? or different workarounds? I'd like to avoid having to put a validation loop like this for every rat1-3

<% unless name.rat1.nil? %>
  <%= name.rat1.rating %>
<% end %>

There has to be a simpler way.

Upvotes: 0

Views: 470

Answers (2)

Manoj Monga
Manoj Monga

Reputation: 3083

OFFTOPIC Your table structure is wrong. It should have <thead><tr><th>Name</th><th>Rating1</th>..so on..</tr></thead>

So, in your case you can use the condition while rendering the rating values as:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Rating 1</th>
      <th>Rating 2</th>
      <th>Rating 3</th>
    </tr>
  </thead>
  <tbody>
  <% @names.each do |name| %>
    <tr>
      <td><%= name.nametext %></td>
      <td><%= name.rat1.rating || 'N/A' %></td>
      <td><%= name.rat2.rating || 'N/A' %></td>
      <td><%= name.rat3.rating || 'N/A' %></td>
    </tr>
  <% end %>
  </tbody>
</table>

Upvotes: 3

blamattina
blamattina

Reputation: 306

I would probably create a helper method in names_helper.rb

def show_rating(rating)
  if rating.present?
    rating
  else
    "default value"
  end
end

Then use it in the view:

<%= show_rating name.rat1.rating %>

Upvotes: 5

Related Questions