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?

Answers


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.


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.