如何翻译ActiveRecord模型类名?

时间:2022-10-04 15:37:28

What is the simplest way to get translated name of ActiveRecord model class when I have an instance of it?

当我有一个ActiveRecord模型类的实例时,最简单的方法是什么?

For example - I have model class like this:

例如,我有这样的模型类:

class Category < ActiveRecord::Base
  ...
end

I have an instance of the class:

我有一个班级的例子:

category = Category.first

And I have YAML file config/locales/cs.yml:

我有YAML文件配置/locale /cs.yml:

cs:
  activerecord:
    models:
      category: Kategorie

And I need to do this dynamicaly, even when I don't previously know with what model class' instance I will be dealing. So I don't want to explicitly specify "activerecord.models.category".

我需要做这个动态的,即使我之前不知道我要处理什么模型类的实例。我不想明确指定"activerec .models.category"

Is there an easy way to do this? I know, that I can do something like this

有简单的方法吗?我知道,我可以做这样的事情

"activerecord.models.#{category.class.name.underscore}"

But there has to be a better way to do this.

但必须有更好的方法来做到这一点。

3 个解决方案

#1


83  

See:

看到的:

http://api.rubyonrails.org/classes/ActiveModel/Naming.html http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

http://api.rubyonrails.org/classes/ActiveModel/Naming.html http://guides.rubyonrails.org/i18n.html translations-for-active-record-models

So, for example, on an AR class use:

例如,在AR类中使用:

Person.model_name.human

or from an AR instance:

或以AR为例:

person.class.model_name.human

#2


0  

Check out constantize and classify.

检查稳定性和分类。

#3


0  

Rails 5:

Rails 5:

you can use category.class.name

您可以使用category.class.name

#1


83  

See:

看到的:

http://api.rubyonrails.org/classes/ActiveModel/Naming.html http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

http://api.rubyonrails.org/classes/ActiveModel/Naming.html http://guides.rubyonrails.org/i18n.html translations-for-active-record-models

So, for example, on an AR class use:

例如,在AR类中使用:

Person.model_name.human

or from an AR instance:

或以AR为例:

person.class.model_name.human

#2


0  

Check out constantize and classify.

检查稳定性和分类。

#3


0  

Rails 5:

Rails 5:

you can use category.class.name

您可以使用category.class.name