49

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

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:

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".

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.

Lukáš Voda
  • 1,262
  • 1
  • 13
  • 13

2 Answers2

97

See:

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:

Person.model_name.human

or from an AR instance:

person.class.model_name.human
Jo P
  • 1,656
  • 21
  • 25
  • Instead of `human`, which adds spaces and downcases all but the first letter, I found `name` to be more useful. So: `SomePerson.model_name.name` which returns `SomePerson` – Matthew Hinea Sep 14 '17 at 21:01
-1

Check out constantize and classify.

Benjamin Tan Wei Hao
  • 9,621
  • 3
  • 30
  • 56
  • Thanks you for answer. But these methods do not solve this problem. As I mentioned, I can use [underscore](http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-underscore) and construct the actual "path" to translation. But I ask, if there is some method that can directly translate model instance (or the model class itself). – Lukáš Voda Jul 25 '12 at 08:58