如何在数据库表中填充i18n下拉菜单

时间:2014-10-05 19:39:18

标签: ruby-on-rails drop-down-menu model internationalization simple-form

我的表单带有下拉菜单,该菜单是从模型填充的:

<%= f.association :cargo_price, :label_method => :price, :value_method => :id %>

有一个名为 cargo_price 的模型,只有 ID 价格列。我想这个选择。这种情况有没有最好的做法?

我想知道将 price 列重命名为 price_en ,并将另一种语言变体添加为单独的列。但我不知道,如何指示 simple_form 将正确的列加载为标签。

2 个答案:

答案 0 :(得分:1)

我必须根据已经解决的类似问题自己解决问题,在互联网论坛和QA上进行了描述。先决条件是,有CargoPrice模型,有3条记录:

ID | Price
---------------
 1 | all_in
 2 | plus_plus
 3 | make_offer

首先,我在 CargoPrice 模型中创建了新方法,此方法名为 translated_price

def translated_price
  I18n.t(price, :scope => 'cargo_price')
end

下一步是定义 en.yaml /其他语言文件的正确翻译:

en:
  cargo_price:
    all_in: "All in"
    plus_plus: "++"
    make_offer: "Make an offer"

最后一步是将表单更改为(注意 label_method ):

<%= f.association :cargo_price, label_method => :translated_price, :value_method => :id %>

现在,从模型中填充下拉选择框,并翻译每个可选择的选项。

答案 1 :(得分:0)

看看Rails Internationalization guide。惯例是使用Rails翻译助手:

I18n.t 'store.title'

翻译yaml文件中的这些参考值:

en:
  store:
    title: "Example Store"
de:
  store:
    title: "Beispiel Speicher"

在您的情况下,听起来您希望将翻译应用于模型列名称。我不建议这样做,你的cargo_price模型应该是相同的,无论它被翻译成什么语言。