在视图中呈现模型属性键名的最佳方法?

时间:2017-06-06 13:46:23

标签: ruby-on-rails model attributes interpolation

我正在编写show和index视图来渲染模型对象,而不是将模型属性标题名称硬编码到视图中我想找到一种更好的方法来渲染这些标题并将它们分配给它们的相关变量以供将来渲染使用

您能否就最佳实践解决方案提出建议?

旧硬编码:

<tr>
  <td>Company name</td> # Would like to interpolate readable vers of attr key here.
  <td><%= @quote.co_name %></td>
</tr>
<tr>
  <td>Company number</td>
  <td><%= @quote.co_number %></td>
</tr>
<tr>
  <td>Office postcode</td>
  <td><%= @quote.postcode %></td>
</tr>
<tr>
  <td>Industry</td>
  <td><%= @quote.industry %></td>
</tr>

1 个答案:

答案 0 :(得分:5)

如果您不想对列名进行硬编码,但希望它们具有可读性,则可以使用ActiveRecord翻译

en:
  activerecord:
    attributes:
      quote:
        co_name: "Company name"
        co_number: "Company number"
        postcode: "Office postcode"
        industry: "Industry"

使用human_attribute_name显示本地化属性名称

<tr>
  <td><%= Quote.human_attribute_name(:co_name) %></td>
  <td><%= @quote.co_name %></td>
</tr>

注意:使用此格式的优点是您还可以在

中获得正确的名称
@quote.errors.full_messages
#=> ["Company name can't be blank", "Company number can't be blank"]
相关问题