Alexandru Para
Alexandru Para

Reputation: 139

Dynamic column name

I try to work with locale:

In routes.rb I have:

scope "(:locale)", :locale => /en|ro|ru/ do
  resources :catalogs
end

In *application_controller.rb* I have

# tell the I18n library where to find your translations
I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]

# set default locale to something other than :en
I18n.default_locale = :en

before_filter :set_locale

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

In the database I have a table with columns: catalog_name_en; catalog_name_ro and catalog_name_ru

In the view list.html.erb I add this code:

<% @catalogs.each do |catalog| %>

    <tr>
        <td class="center"><%= catalog.id %></td>
        <td class="center"><%= "catalog.catalog_name#{locale}" %> </td>
    </tr>
<% end %>

In the html page I see only "catalog.catalog_name_en", but not the value for the column catalog_name_en . Help me PLZ.

Upvotes: 3

Views: 1267

Answers (2)

Romain
Romain

Reputation: 12809

You can try using:

<%= catalog.attributes["catalog_name_#{locale}"] %>

Or a shorter, but equivalent (as noted in comments):

<%= catalog["catalog_name_#{locale}"] %>

Upvotes: 6

Mischa
Mischa

Reputation: 43298

You can also use send:

catalog.send("catalog_name_#{locale}")

Upvotes: 1

Related Questions