Question

im writing a app using rails an i18n , i already have translated the countries in 6 lenguajes, and they all are in each own yml file with all other lenguaje stuff..

My question is how can i order , and reorder depending on the lenguage, (english, spanish, french, arabic, Chinese, Portuguese )

I think i can set a code for ordering the list here right? , but how?

{|p| [ t("generales."+p.iso), p.id ] }

Here is my code in view , where that line is

  <div >
 <%= f.fields_for :citizens do |citizen_form| %>

    <div>
      <%= citizen_form.label  :citizen, t('generales.citizen')  %>
      <%= citizen_form.select :country_id , Country.all.collect {|p| [ t("generales."+p.iso), p.id ] }, { :include_blank => true } , { :class => 'pca33' } %>
      <div id="delerr"><%= citizen_form.link_to_remove t('generales.delete') %></div>
    </div>

  <% end %>

  <%= f.link_to_add t('generales.add'), :citizens %>
  </div>

Here is model

class Citizen < ActiveRecord::Base
  attr_accessible  :country_id

  belongs_to :player
  belongs_to :country
end

In the en.yml file i have like this the translate, it look for the iso in database, so as you can see the list is based on iso.

AF: 'Afghanistan'
    AL: 'Albania'
    DZ: 'Algeria'
    AD: 'Andorra'
    AO: 'Angola'
    AG: 'Antigua and Barbuda'
    AR: 'Argentina'
    AM: 'Armenia'
    AU: 'Australia'
    AT: 'Austria'
    AZ: 'Azerbaijan'
    BS: 'Bahamas'
    BH: 'Bahrain'
    BD: 'Bangladesh'
    BB: 'Barbados'
    BY: 'Belarus'
    BE: 'Belgium'
    BZ: 'Belice' 
Was it helpful?

Solution

Use sort_by to sort the list, and iconv to ignore the accented characters:

require 'iconv'
...

@countries = Country.all.collect {|p| [ t("generales."+p.iso), p.id ] }
@countries = @countries.sort_by {|label,code| Iconv.iconv('ascii//ignore//translit', 'utf-8', label).to_s}

Usually this code is put in the controller or in a helper, instead of directly in the view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top