在Rails中按字符串翻译模型名称

时间:2015-07-27 11:55:17

标签: ruby-on-rails

有以下代码:

model_name = self.class.name.demodulize.sub("Controller", "").singularize
message = t('activerecord.exceptions.not_found', model_name: model_name) 
render json: message, status: :not_found

还有一些YAML:

ru:
  activerecord:
    exceptions:
      not_found: "%{model_name} не найден"

正如您所看到的,我在翻译中有俄文文本,但模型名称仍为英文。我怎么能用俄语翻译模型名称呢?提前谢谢!

1 个答案:

答案 0 :(得分:1)

ru:
  activerecord:
    models:
      user: пользователь
model_name = self.class.name.demodulize.sub("Controller", "").singularize
model_klass = model_name.constantize
message = t(
 'activerecord.exceptions.not_found', 
 model_name: model_klass.model_name.human
) 
render json: message, status: :not_found
  

http://guides.rubyonrails.org/i18n.html