/en|ro|ru/ do resources :cat...">

Dynamic column name

I am trying to work with the language:

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_en

In 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 catalog_name_en column. Help me plz.

+3
source share
2 answers

You can try:

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

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

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

You can also use send:

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

All Articles