加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在视图中呈现模型属性键名的最佳方法?

发布时间:2020-12-17 02:57:05 所属栏目:百科 来源:网络整理
导读:我正在编写show和index视图来渲染模型对象,而不是将模型属性标题名称硬编码到视图中我想找到一种更好的方法来渲染这些标题并将它们分配给它们的相关变量以供将来渲染使用. 您能否就最佳实践解决方案提出建议? 旧硬编码: tr tdCompany name/td # Would like
我正在编写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>

解决方法

如果您不想对列名进行硬编码但希望它们可读,则可以使用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"]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读