How am I supposed to write the forms for my models where I'm using rails 4 and https://github.com/globalize/globalize for translations. i want to display all translations in one form like below example. i have found a solution here https://github.com/rilla/batch_translations but i don't know how do i implement this. is this "batch translation" a gem or what? and how can i install it.
<h1>Editing post</h1>
<% form_for(@post) do |f| %>
<%= f.error_messages %>
<h2>English (default locale)</h2>
<p><%= f.text_field :title %></p>
<p><%= f.text_field :teaser %></p>
<p><%= f.text_field :body %></p>
<hr/>
<h2>Spanish translation</h2>
<% f.globalize_fields_for :es do |g| %>
<p><%= g.text_field :title %></p>
<p><%= g.text_field :teaser %></p>
<p><%= g.text_field :body %></p>
<% end %>
<hr/>
<h2>French translation</h2>
<% f.globalize_fields_for :fr do |g| %>
<p><%= g.text_field :title %></p>
<p><%= g.text_field :teaser %></p>
<p><%= g.text_field :body %></p>
<% end %>
<% end %>
The batch translation gem is quite old and I've had difficulties using it with newer versions of Rails. I stumbled on another gem called globalize-accessors which supports Rails 4. What's great is that it gives you access to methods like title_en
, teaser_es
, title_fr
and so on.
So for example if you had a Feature model with names that should be in all languages you could to the following:
# => Feature Model (feature.rb)
class Feature < ActiveRecord::Base
translates :name
globalize_accessors :attributes => [:name]
end
Using the Feature.globalize_attribute_names
method would give an array of [:name_en, :name_es, :name_fr]
that can be used in the form_for helper:
//New Feature (new.html.haml)
= form_for @feature do |f|
- Feature.globalize_attribute_names.each do |lang|
= f.text_field lang
= f.submit
Have you considered something like this?
<%= form_for(@post) do |f| %>
<%= f.error_messages %>
<% [:en, :es, :fr].each do |lang| %>
<h2><%= lang %> translation</h2>
<% f.globalize_fields_for lang do |g| %>
<% [:title, :teaser, :body].each do |field| %>
<p><%= g.text_field field %></p>
<% end %>
<% end %>
<hr/>
<% end %>
<% end %>
You should be able to get those lists of regions and fields automatically. Then you only need a map of region to language name, like { en: 'English', es: 'Spanish', fr: 'French'}
and you can output the proper language name instead of the region code. (This might already be available somewhere as well.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With