tessad
tessad

Reputation: 1229

looping and only displaying attributes which are present

I am trying to only show the attributes that are present on my index page. Here is my code so far, and it does work:

<% @contacts.each do |contact| %>
<strong>Name: <%= contact.name %></strong>

<% if contact.phone %>
  <p>Phone number: <%= contact.phone !="nil" %></p>
<% end %>
<% if contact.category !="nil" %>
  <p>Category: <%= contact.category %></p>
<% end %>
<% if contact.area !="nil" %>
  <p>Area: <%= contact.area %></p>
<% end %>
<% if contact.website !="nil" %>
  <p>Website: <%= contact.website %></p>
<% end %>
<% if contact.email%>
  <p>Email: <%= contact.email !="nil" %></p>
<% end %>
<% end %>

My questions is

Is there a neater way for me do this (i.e. rather than specifying the if for each attribute)?

Thanks

Upvotes: 0

Views: 25

Answers (1)

usha
usha

Reputation: 29369

<% @contacts.each do |contact| %>
  <strong>Name: <%= contact.name %></strong>
  <%["phone", "category", "area", "website", "email"].each do |attr| %>
    <% unless contact.send(attr).blank?%>
      <p>
       <%= attr.capitalize%>
      </p>
      <%= contact.send(attr.to_sym)%>
    <% end %>
  <% end %>
<% end %>

Upvotes: 2

Related Questions