ruby-on-railscountries

Countries gem rails


I am using countries gem to list countries in a dropdown,

<%= form.collection_select(:country, ISO3166::Country.countries.sort_by(&:name), 'name', 'name', {include_blank: 'Select a country'}, class: "select__picker", 'data-style': 'form-control', required: true) %>

Is there any ways to display country name with country emoji at dropdown


Solution

  • Yes, there is a way.

    <%= f.collection_select(:country, ISO3166::Country.countries.sort_by(&:name).collect { |c| [ c.name, "#{c.name} #{c.emoji_flag}" ] }, :first, :last, {include_blank: 'Select a country'}, class: "select__picker", 'data-style': 'form-control', required: true) %>
    

    collection_select accepts only a method name as a text_method param. The text_method is called on the collection param, which is:

    ISO3166::Country.countries.sort_by(&:name).collect { |c| [ c.name, "#{c.name} #{c.emoji_flag}" ] }
    

    So in your case, you are calling :first for the value and :last for the option text on:

    [
      ['COUNTRY_1_NAME', 'COUNTRY_1_NAME COUNTRY_1_FLAG'],
      ['COUNTRY_2_NAME', 'COUNTRY_2_NAME COUNTRY_2_FLAG']
      etc.
    ]