views:

41

answers:

2

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.

A: 
show_field_unless_empty(blog, :body, 'Body')

then, in blog_helper.rb

def show_field_unless_empty(model, field, title)
  render :partial => 'field', :locals => {:value => model.send(field), :title => title} if model.send(field)
end

then, in _field.html.erb

<p>
<%= title %>: 
<%= value %>
</p>

This seems fairly clean to me.

Evgeny Shadchnev
Sorry, that doesn't really work. It gives me the same value as before.
Senthil
+1  A: 

I would do it like this:

# blog_helper.rb
show_non_blank_field(label, value)
  "<p>#{label}: #{h value}</p>" if !value.blank?
end

and then in view:

<%= show_non_blank_field "Body", blog.body %>

and so on...

Of course you can use shorter helper name.

If you want to do it in if-else way, try this:

<% if !blog.title.blank? -%>
 <p>Title: <%=h blog.title %></p>
<% end %>

<% if !blog.body.blank? %>
 <p>Body: <%=h blog.body %></p>
<% end %>

<p>Comments: <%=h blog.comments %></p>
klew
That works perfectly. Thanks!
Senthil
As a slight variation on that theme, you could use "content_tag" (either in the helper or in the view) to remove the embedded HTML, as in something like:content_tag(:p, "%s: %s" % [label, value]) unless value.blank?
NeilS
I didn't know content_tag could be used like that. Thanks. What about sql injection. I assume using %s instead of label or value takes care of that.
Senthil
@Senthil: You don't have to care about label as long as it is always typed in views (not from user editable field in db). I don't know if label or value from @NeilS example is escaped, but you always can use `[h(label), h(value)]`
klew
Oh yea right. I was talking about value. Thanks again.
Senthil