2017-06-06 24 views
4

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

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

老硬编码:

<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

看看这个:http://blog.brzezinka.eu/webmaster-tips/ruby/ruby-on-rails -i18n-form-labels –

回答

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"] 
+0

非常好,谢谢你们。 – jbk

相关问题