将哈希传递给i18n翻译

时间:2015-04-28 07:32:12

标签: ruby-on-rails ruby internationalization rails-i18n

我在创建通知系统的过程中。系统应该通知用户模型中的一些更改,即这是我的.yml文件

ru:
  notifications:
    task: "New task named %{notifiable.task_name}"
    order: "New order with price %{notifiable.price}"

您现在了解我有一个关联User has_many NotificationNotification has_one(polymorphic) Notifiable。因此,您了解Order没有归属task_nameTask没有归属price。如何将哈希传递给i18n或以另一种方式实现此逻辑?

1 个答案:

答案 0 :(得分:0)

哦,明白了!

请考虑以下代码:

# making a hash
def serialized_message_object
  attr_hash = {}
  @user.attribute_names.each { |attr_name| attr_hash[('user_' + attr_name).to_sym] = @user[attr_name] }
  @user.attribute_names.each { |attr_name| attr_hash[('notifiable_' + attr_name).to_sym] = @notifiable[attr_name] }
  attr_hash 
end

# call I18n
I18n.t('notifications.' + message_type, serialized_message_object)

# i18n
ru:
  notifications:
    task: "New task named %{notifiable_task_name}"
    order: "New order with price %{notifiable_price}"