小编yer*_*ips的帖子

使用Ruby/Rails将嵌套哈希展平为单个哈希

我想在.flatten不同深度的哈希中"扁平化"(不是在经典意义上),如下所示:

{
  :foo => "bar",
  :hello => {
    :world => "Hello World",
    :bro => "What's up dude?",
  },
  :a => {
    :b => {
      :c => "d"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

下到一个单一级别的哈希,并且所有嵌套的键合并为一个字符串,因此它将成为:

{
  :foo => "bar",
  :"hello.world" => "Hello World",
  :"hello.bro" => "What's up dude?",
  :"a.b.c" => "d"
}
Run Code Online (Sandbox Code Playgroud)

但我想不出一个好办法.它有点像deep_Rails添加到Hashes 的辅助函数,但不完全相同.我知道递归将是这里的方式,但我从未在Ruby中编写过递归函数.

ruby recursion ruby-on-rails

17
推荐指数
3
解决办法
8894
查看次数

帮助i18n在form_for之外翻译模型属性?

我有一个名为的模型Presentation.它的所有属性都在我的i18n语言环境文件中命名activerecord.attributes.presentation.

我想以表概述的形式为此模型创建索引视图.目前的代码如下所示:

<table class="table">
  <thead>
    <tr>
      <th><%= t('activerecord.attributes.presentation.title') %></th>
      <th><%= t('activerecord.attributes.presentation.default_duration') %></th>
      <th><%= t('activerecord.attributes.presentation.bg_color') %></th>
    </tr>
  </thead>

  <tbody>
    <%= render @presentations %>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

哪个工作正常,但必须写出完整的密钥似乎并不像我的Rails方式.如果缺少翻译,或者模型的这种属性不存在,它也不会以任何明显的方式失败.

<%= f.label :title %>form_for块内部会根据符号自动将已翻译的属性名称输出为标签.是否有任何类型的视图帮助程序以相同的方式工作,但在表单之外?像这样的东西(这不是最好的代码示例,我知道):

<%= attributes_of User do |attr| %>
  <th><%= attr.t :title %></th>
  <th><%= attr.t :default_duration %></th>
  <th><%= attr.t :bg_color %></th>
<% end %>
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails

0
推荐指数
2
解决办法
1280
查看次数

标签 统计

ruby-on-rails ×2

recursion ×1

ruby ×1