IT_puppet_master
IT_puppet_master

Reputation: 702

I18n to call different Model Attribute depending on Locale?

So I am building an on-line shop and I want two language options, English and Spanish.

I am using I18n as you would normally do for all my static text and headings ect.

But, I have a products Model that can have new Products created for listing on the site. This has fields like :name_en and :name_es, :description_en and :description_es ect.

When the admin uploads a new product they obviously need to add the English and the Spanish text.

Because I have only 2 locales what I would like to do i think is call something like

    <%= Product.name_"#{I18n.locale.downcase}" %>

But obviously this does not work. How can i, or just can I, interpolate a method or Attribute?

Have I missed something obvious here and just going about it the wrong way or is there a way to do this along the lines of my thinking?

Any Help massively appreciated.

Thanks

Upvotes: 0

Views: 148

Answers (1)

Paweł Dawczak
Paweł Dawczak

Reputation: 9639

You can use send method. Try something like:

<%= Product.send("name_#{I18n.locale.downcase}") %>

Just a word of explanation, the following are equal:

string = "Hello"

string.upcase
# => "HELLO"

string.send("upcase")
# => "HELLO"

Hope that puts you in proper direction!

Good luck!

Upvotes: 1

Related Questions