仅显示Rails中存在的属性

时间:2014-11-05 16:20:19

标签: ruby-on-rails ruby rails-activerecord

在我的展示视图中,我有一些不需要由用户填写的属性。在我的节目视图中,我可以轻松创建一个条件,如下所示:

<% if @user.occupation.present? %>
    <p><%= @user.occupation %></p>
<% end %>

但如果我有3个或更多这些可选属性,为每个属性创建多个条件可能会变得非常繁琐。我想过做这样的事情,但事实证明方法attribute是私有的:

<% @user.attributes.map do |attribute, name| %>
  <% if @user.attributes.present? %>
    <p><b><%= name %>:</b> <%= @user.attribute %></p>
  <% end %>
<% end %>

出于安全考虑,我并不一定试图将属性方法更改为私有方法,而是更多地寻找一种方法来列出已填写的模型属性。

1 个答案:

答案 0 :(得分:1)

<% @user.attributes.each do |key, value| %>
  <% if value.present? %>
    <p><b><%= key %>:</b> <%= value %></p>
  <% end %>
<% end %>