neezer neezer - 3 months ago 10
Ruby Question

Rails: How do I check if a column has a value?

How can I accomplish this?

<% for agent in @broker.agents %>
...
<% if agent.cell %><span class="cell-number">Cell: <%= agent.cell %></span><% end %>
...
<% end %>


I want to test to see if the agent has a cell number, and if so, display what's inside the conditional. What I have currently doesn't seem to work; it just displays "Cell: ".

Thoughts?

Answer

This is what you asked for:

<% for agent in @broker.agents %>
  <% unless agent.cell.blank? %>
    <span class="cell-number">Cell: <%= agent.cell %></span>
  <% end %>
<% end %>

The cell? method works whether cell is nil or an empty string. Rails adds similar functions for all ActiveRecord attributes. This will look a little nicer:

<% for agent in @broker.agents %>
  <span class="cell-number">
    Cell: <%= agent.cell? ? "none given" : agent.cell %>
  </span>
<% end %>

The question mark and colon form a quick "if ? then : else" statement. There are two question marks in the code above because one is part of the method name cell? and the other is a part of the if/then/else construction.