ruby-on-railsruby-on-rails-5mobility

How to implement all translations in one form with Mobility gem in Rails?


In my Rails app i'm using Mobility gem for translations

How to build a form with all translations, like:

What is the best way?


Solution

  • There's not really any documentation about this, but it's not difficult to create a form like that with Mobility.

    Here's an example, assuming you have an object @post with a translated attribute title:

    <%= form_for @post do |f| %>
      <% I18n.available_locales.each do |locale| %>
        <div>
          <% attr_name = "title_#{Mobility.normalize_locale(locale)}" %>
          <%= f.label attr_name %>
          <%= f.text_field attr_name %>
        </div>
      <% end %>
    
      <%= f.submit %>
    <% end %>
    

    In your controller you'll have to permit the localized attribute names as well, something like:

    def update
      # ...
      @post.update(permitted_params)
      # ...
    end
    
    # ...
    
    private
    
    def permitted_params
      params.require(:post).permit(I18n.available_locales.map { |l|
        :"title_#{Mobility.normalize_locale(l)}"
      })
    end