Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I translate ActiveRecord model class name?

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.

like image 620
Lukáš Voda Avatar asked Jul 20 '12 17:07

Lukáš Voda


People also ask

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is an ActiveRecord object?

In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic as part of the object will educate users of that object on how to write to and read from the database.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is model in Ruby on Rails?

A model is a Ruby class that is used to represent data. Additionally, models can interact with the application's database through a feature of Rails called Active Record. To define a model, we will use the model generator: $ bin/rails generate model Article title:string body:text Copy.


1 Answers

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 
like image 165
Jo P Avatar answered Oct 09 '22 20:10

Jo P