【问题标题】:Passing a hash to i18n translation将哈希传递给 i18n 翻译
【发布时间】:2015-04-28 07:32:12
【问题描述】:
我正在创建通知系统。系统应该通知用户模型的一些变化,即这是我的.yml 文件
ru:
notifications:
task: "New task named %{notifiable.task_name}"
order: "New order with price %{notifiable.price}"
您现在明白了,我有一个关联 User has_many Notification 和 Notification has_one(polymorphic) Notifiable。所以,你知道Order 没有属性task_name 和Task 没有属性price。如何将哈希传递给 i18n 或以其他方式实现此逻辑?
【问题讨论】:
标签:
ruby-on-rails
ruby
internationalization
rails-i18n
【解决方案1】:
哦好的明白了!
请考虑以下代码:
# 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}"