开发者

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

开发者 https://www.devze.com 2022-12-27 12:56 出处:网络
Say I\'ve a user model and there are bunch of user info, like email, birthdate, location, telephone number etc.开发者_开发问答

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.


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>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号