Ruby-on-rails 如何翻译 ActiveRecord 模型类名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11584489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I translate ActiveRecord model class name?
提问by Luká? Voda
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 文件config/locales/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".
而且我需要动态地做到这一点,即使我以前不知道我将处理哪个模型类的实例。所以我不想明确指定“activerecord.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.
但是必须有更好的方法来做到这一点。
回答by Jo P
See:
看:
http://api.rubyonrails.org/classes/ActiveModel/Naming.htmlhttp://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
回答by Benjamin Tan Wei Hao
Check out constantizeand classify.
回答by Mayur Patel
Rails 5:
导轨 5:
you can use category.class.name
您可以使用 category.class.name

