Only show non blank attributes for a model in views in Rails

Posted by Senthil on Stack Overflow See other posts from Stack Overflow or by Senthil
Published on 2010-04-15T10:55:10Z Indexed on 2010/04/15 11:13 UTC
Read the original article Hit count: 263

Filed under:

Say I've a user model and there are bunch of user info, like email, birthdate, location, telephone number etc.

What's the simplest way of hiding the attributes that are blank?

I've doing something like

<% if blog.title.empty? -%>
 <p>Body: <%=h blog.body %></p>
 <p>Comments: <%=h blog.comments %></p>

<% elsif blog.body.empty? %>
 <p>Title: <%=h blog.title %></p>
 <p>Comments: <%=h blog.comments %></p>

<% else -%>
 <p>Title: <%=h blog.title %></p>
 <p>Body: <%=h blog.body %></p>
<% end -%> 

Clearly that is one ugly child. Other than using partials to render, is there a trick to only show non blank fields?

I've been trying to write a helpher method to make the view cleaner, but that's even more ugly.

Any help is appreciated.

© Stack Overflow or respective owner

Related posts about ruby-on-rails