Note that there are some explanatory texts on larger screens.

plurals
  1. POMatching available languages to language names
    text
    copied!<p>I want to make a language selection dropdown in a site user edit/create page.</p> <p>For this purpose, I have of course translated the site to more than one language. Using I18n.available_languages, I can then get an array of locale codes, like so</p> <pre><code>development environment (Rails 2.3.4) &gt; I18n.available_locales =&gt; [:en, :da] </code></pre> <p>Furthermore, I have created a Language model and related it to User:</p> <pre><code># app/models/language.rb class Language &lt; ActiveRecord::Base has_many :users end # app/models/user.rb class User &lt; ActiveRecord::Base belongs_to :language end # db/schema.rb create_table "languages", :force =&gt; true do |t| t.string "name" t.string "code" end create_table "users", :force =&gt; true do |t| t.integer "language_id" end </code></pre> <p>The language table then contains a locale code and a language name in the native tongue, like so:</p> <pre><code>| id | name | code | ------------------------------------ | 28 | Dansk | da | | 29 | Nederlands | nl | | 30 | English | en | | 31 | Esperanto | eo | </code></pre> <p>I then have the following assignment in the User new, create and edit actions:</p> <pre><code># app/controllers/users_controller.rb (extract) @available_languages = I18n.available_locales.collect {|language_code| Language.find_by_code(language_code.to_s)} </code></pre> <p>which I use in the view like so ('available_languages' is a local variable, since @available_languages from the controller has been passed to a partial):</p> <pre><code># app/views/users/_form.haml (extract) = f.collection_select(:language_id, available_languages, :id, :name, {:prompt =&gt; true}) </code></pre> <p>The upshot of all this, is that the user will get a locale select dropdown to define the locale for the given user.</p> <p>My question is: Is there a clean way to move the @available_languages assignment out of the UsersController and into the Language model, so I can shorten this:</p> <pre><code>@available_languages = I18n.available_locales.collect {|language_code| Language.find_by_code(language_code.to_s)} </code></pre> <p>to something like this:</p> <pre><code>@available_languages = Language.translations_available </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload