Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 292
Alexandru Para Avatar asked Aug 25 '26 19:08

Alexandru Para


2 Answers

You can try using:

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

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

<%= catalog["catalog_name_#{locale}"] %>
like image 141
Romain Avatar answered Aug 27 '26 18:08

Romain


You can also use send:

catalog.send("catalog_name_#{locale}")
like image 37
Mischa Avatar answered Aug 27 '26 17:08

Mischa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!