简体   繁体   中英

Rails: how to use language list gem with select_tag in a form?

I'm in the middle of trying to create a form where one of the questions is to choose a specific language. I'm trying to use the language list gem here: https://github.com/scsmith/language_list . However, the documentation doesn't really show me how I would combine the list with a select_tag.

<%= form_for users_path, :method => "get" do %>

    <%= label_tag "Select Country" %> <br>
    <%= country_select(:user, :country, [], :include_blank => true) %> <br>

    <%= label_tag "Language spoken" %>
    <%= select_tag "Language", options_from_collection_for_select(LanguageList::COMMON_LANGUAGES, "id", "name") %>

    <%= label_tag "City" %> <br>
    <%= text_field_tag(:city) %>


<% end %>

gives me the error

undefined method 'id' for afr (af) - Afrikaans:LanguageList::LanguageInfo

on the line

<%= select_tag "Language", options_from_collection_for_select(LanguageList::COMMON_LANGUAGES, "id", "name") %>

Can anyone help me?

Don't use "id" . The docs say you should use iso_639_1 (or iso_639_3 if you want 3-letter codes)

<%= select_tag "Language", options_from_collection_for_select(LanguageList::COMMON_LANGUAGES, "iso_639_1", "name") %>

The LanguageList class seems to return a hash of LanguageInfo instances, having attributes like name, type and code -- `options_from_collection_for_select' expects its first parameter to be the collection (the hash in this case), the second a method that will return the value you want to identify the item, and the third is a display string.

So when someone selects a language, what are you going to store in the database? Probably one of the codes, right? So in this were true, you would make the second argument a method that an instance of the collection would respond to, which (reading the source code of the gem) is either iso_639_1 or iso_639_3 . name should already work.

So if you replace id with one of those two iso_nnn_n values, then the form should display. To actually save the language code in the database, you'll need a column in your database for it, which you may already have as language .

Sometimes it's make a lot of sense to store gem's data dump in the database.

here is sample with postgresql and rails https://github.com/serghei-topor/import-language-list-into-db-rails-sample

here is csv file of gem's data dump https://github.com/serghei-topor/language-list-csv

And select_tag will look like:

<%= select_tag "Language", options_from_collection_for_select(Language.where(is_common:true).order(:name), "id", "name") %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM