带有I18n数据的种子轨道数据库

问题描述

在rails 5.2上,我想用:en和:pt语言填充数据库,我尝试:

Product.create!(
  process:  t('washed'),category: coffee)

,然后在en.yml和pt.yml文件中提供翻译。我收到此错误消息:

NoMethodError: undefined method `t' for main:Object

有什么想法吗?

-编辑----

我认为Ifound提供了解决方案,但无法使其与嵌套属性一起使用:

在我的seed.rb中:

Product.create!(
 name:'Cerro de Jesus farm',process: I18n.t('process'),cupping_notes: I18n.t('cup_notes.nica_cp'),category: coffee)

在我的pt.yml中:

pt:
 process: "lavado"
 cup_notes:
  nica_cp: 'café,limão'
  columb_cp: 'limão'

在我看来:

<p><%= t('cup_notes',cupping_notes:@product.cupping_notes)%></p>

该视图显示整个哈希:拔罐笔记:{:nica_cp =>“café,limão”,:columb_cp =>“limão”}

对我错过的事情有任何想法吗?谢谢!

解决方法

tI18n.t的简写,但仅适用于视图和帮助器。在控制器或模型中,请使用I18n.t

https://guides.rubyonrails.org/i18n.html#the-public-i18n-api

如果希望将此部分纳入您的观点,则需要执行以下操作:

pt.yml

pt:
 process: "lavado"
 cup_notes:
  nica_cp: 'café,limão'
  columb_cp: 'limão'

您认为:

<p><%= t("cup_notes.#{@product.cupping_notes}")%></p>

供参考

您尝试使用:

<p><%= t('cup_notes',cupping_notes:@product.cupping_notes)%></p>

不起作用,因为第二个参数用于将变量传递给特定的翻译。

例如,如果我的翻译中有此内容:

pt:
  number_of_lemons: "%{number} limões"
``

Then I can do this in my view:

```

有关更多信息,请参见Translation Variables