将哈希传递给 i18n 翻译

Passing a hash to i18n translation

我正在创建通知系统。系统应通知用户有关模型的一些更改,即这是我的 .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 或以其他方式实现此逻辑?

哦好的明白了!

请考虑以下代码:

# 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}"