views:

774

answers:

4

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?

+1  A: 
if !agent.cell.blank?

Works. Sweet.

neezer
You might consider "unless agent.cell.blank?", which some assert is "more Ruby-ish"
James A. Rosen
I use unless unless agent.cell.blank because double negatives are awesome.
FlySwat
+1  A: 

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.

Adrian Dunston
+1  A: 

agent.cell? seems to work the same as agent.cell.blank? in RoR.

Farrel
A: 
<% @broker.agents.each do |agent| %>
  ...
  <% unless agent.cell.empty? %>
    <span class="cell-number">Cell: <%= agent.cell %></span>
  <% end %>
  ...
<% end %>

I find the use of #each, unless, and cell.empty? to be more readable and easier to understand at first glance.

Sarah Vessels