'How to apply i18n to Rails Ransack's dropdown menu

I have a drop-down menu (to select the state) in the search function form of a web page (view), specifically a set of key-values. The code is as follows:

<%= search_form_for(@query, url: list_tasks_path) do |f| %>
  <%= f.label :name, t('search') %>
  <%= f.search_field :name_cont, placeholder: t('task_title') %>
  <%= f.select :status_eq, Task.statuses.map { |key, value| [key.titleize, value] }, prompt: t('all_status') %> 
  <%= f.submit %>
<% end %>

I want to make the status option apply i18n, so I changed the code to the following, but it didn't work

<%= search_form_for(@query, url: list_tasks_path) do |f| %>
  <%= f.label :name, t('search') %>
  <%= f.search_field :name_cont, placeholder: t('task_title') %>
  <%= f.select :status_eq, Task.statuses.map { |key, value| [t("checkpoint_status.#{key}"), value] }, prompt: t('all_status') %> 
  <%= f.submit %>
<% end %>

This is the enum with the status set on the model

  enum status: { waiting: 0, carry_on: 1, finished: 2 }
  
  def self.i18n_status(hash = {})
    statuses.keys.each { |key| hash[I18n.t("checkpoint_status.#{key}")] = key }
    hash
  end

This is part of my yml file

  all_status: "Select status"
  checkpoint_status:
    waiting: "Waiting"
    carry_on: "Carry on"
    finished: "Finished"

How can I fix it please?



Solution 1:[1]

You could just call the method you defined on your model.

<%= search_form_for(@query, url: list_tasks_path) do |f| %>
  <%= f.label :name, t('search') %>
  <%= f.search_field :name_cont, placeholder: t('task_title') %>
  <%= f.select :status_eq, Task.i18n_status, prompt: t('all_status') %> 
  <%= f.submit %>
<% end %>

The model method could be refactored to the following.

  def self.i18n_status
    statuses.map do |status, idx|
      [I18n.t(status, scope:'checkpoint_status'), idx]
  end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christos-Angelos Vasilopoulos