ruby-on-rails - 将 i18n gem 与邮件一起使用时出现问题

标签 ruby-on-rails ruby ruby-on-rails-3 email internationalization

我正在使用 Ruby on Rails 3.1,我想知道如何正确处理与邮件程序相关的国际化。也就是说,...

...在我的 app/views/users/mailer/_custom.html.erb 文件中我有:

...
<%= @test_email.to_s %>
...

...在我的 app/mailers/users/mailer.rb 文件中我有:

class Users::Mailer < ActionMailer::Base
  def custom(user)
    ...
    @test_email = t('test_email')
    # I also tried to use '@test_email = I18n.t('test_email')'
  end
end

通过使用上面的代码,@test_email.to_s 文本不会在发送的电子邮件中显示(它似乎是空白)并且 I18n gem似乎没有正确完成应该做的事情。 如何解决问题以便在“目标”电子邮件正文中正确显示语言环境消息?


@volodymyr

更新

您在答案中发布的代码对我不起作用。我还尝试将以下代码添加到我的 config/locales/defaults/en.yml 文件中:

en:
  hello: Test text!!!

测试文本!!! 仍然没有显示在发送的电子邮件中(它是空白的)。

最佳答案

这是工作代码的示例(我使用的是 Rails 3.1.0 和 ruby​​ 1.9.3p0(2011-10-30 修订版 33570)):

# Fragment of mailer
def test_locale
    @test_email = I18n.t('hello')
    mail(:to => "<your_email_goes_here>", :subject => "test")
end

# Contents of test_locale.html.erb
String, retrieved from I18n: <%= @test_email %>

为了测试,我使用了 Rails 控制台:

MyMailer.test_locale.deliver

所以你需要检查是否:

  • Erb 模板文件名与邮件程序的方法名匹配
  • 本地化文件中有相应的记录
  • 邮件方法和模板文件中的变量名匹配
  • “views”中的文件夹名称与邮件名称相匹配

更新:尝试在本地化文件中用引号将字符串括起来:

en:
    hello: "Some text here"

关于ruby-on-rails - 将 i18n gem 与邮件一起使用时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8768532/

相关文章:

ruby-on-rails - 使用 Elasticsearch 与 Searchkick on Rails 通过关联查找用户项目?

ruby-on-rails-3 - .where 与 find。 ActiveRecord::关系 NoMethodError

ruby-on-rails - 我应该采取什么步骤来添加我新创建的 Gem?我怎样才能访问它?

ruby-on-rails - Ruby on Rails 中的 Jasper 报告

ruby - 在 Rack 映射中运行多个 Controller

ruby-on-rails - 无法将Rails应用程序连接到Oracle

ruby-on-rails-3 - 计算以天、小时和分钟为单位的时间差

ruby-on-rails - 在 rails 配置文件和 javascript 之间共享变量

ruby-on-rails - 帮助在 Lion GM 上安装 Ruby 1.9.2

ruby-on-rails - rails : Using form_for multiple times (DOM ids)