Display non-empty attributes for a model in views in Rails

Say I have a user model, and there is a ton of user information, such as email, date of birth, location, phone number, etc.

What is the easiest way to hide attributes that are empty?

I'm 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, this is one ugly child. Besides using partial images for rendering, is there a trick to show only empty fields?

I am trying to write a helpher method to make the view cleaner, but it is even more ugly.

Any help is appreciated.

+3
source share
2 answers

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:

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

etc.

Of course, you can use a shorter helper name.

if-else, :

<% 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>
+3
show_field_unless_empty(blog, :body, 'Body')

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

_field.html.erb

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

.

0

Source: https://habr.com/ru/post/1741261/


All Articles