开发者

Sort list based on their i18n translation

Given i have a list of items in my DB and their respective translation in i18n file.

i18n file:

  basic_categories:  
    item_1: Z
    item_2: A
    item_3: F

on the view:

      &l开发者_开发知识库t;% @basic_categories.each do |category| %>
        <%= t("basic_categories.#{category.name}") %>
      <% end %>

How can i sort this list for each language?


You might want to have the translation in your database if your list is too long, for performance reason. MySQL sort faster than ruby.

Otherwise I think you could do something like this:

In your controller, use ruby to build an array of string or hash:

@basic_categories = categories.collect { |category|
  { :name => I18n.t("basic_categories.#{category.name}"), ... }
}.sort_by { |category| category[:name] }

And sort it with ruby, see http://ruby-doc.org/core/classes/Enumerable.html

In you view simply:

<% @basic_categories.each do |category| %>
  <%= category[:name] %>
  ...
<% end %>


Also you can pass json with translations to PG query and then order by translated value from json:

categories_i18n = I18n.backend.instance_variable_get(:@translations).dig(:en, :basic_categories).to_json
@basic_categories = categories.order("'#{categories_i18n}::json'->>name")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜