From 2.4.0 Mongoid now supports localized fields without the need of any external gem.
class Product
include Mongoid::Document
field :description, localize: true
end
By telling the field to localize, Mongoid will under the covers store the field as a hash of locale/value pairs, but normal access to it will behave like a string.
# Using a default locale of en.
product = Product.new
product.description = "Marvelous!"
I18n.locale = :de
product.description = "Fantastisch!"
product.attributes
#=> { "description" => { "en" => "Marvelous!", "de" => "Fantastisch!" }
You can get and set all the translations at once by using the corresponding _translations
method.
product.description_translations
#=> { "description" => { "en" => "Marvelous!", "de" => "Fantastisch!" }
product.description_translations =
{ "description" => { "en" => "Marvelous!", "de" => "Wunderbar!" }
https://github.com/mongoid/mongoid/issues/1770
Instead of the normal field name, use the field translations name. Ie:
class Product
include Mongoid::Document
field :name, localize: true
end
# The getter for all translations:
user.name_translations
# The setter for all translations:
user.name_translations=
You just create an input that will submit to name_translations=
in this case with a hash of locale/value pairs.
class Category
include Mongoid::Document
field :name, type: String, localize: true
end
<%= f.fields_for :name_translations do |fo| %>
<%= fo.label :ru %>
<%= fo.text_field :ru %>
<%= fo.label :en %>
<%= fo.text_field :en %>
<% end %>
when you use simple_form
<%= f.input :change_log do %>
<%= f.fields_for :change_log_translations do |localized_field| %>
<%= localized_field.input "zh-CN", as: :text, input_html: { value: @gxservice_gx_app.change_log_translations["zh-CN"], :rows =>"5", :cols =>"80" } %>
<%= localized_field.input "en", as: :text, input_html: { value: @gxservice_gx_app.change_log_translations["en"], :rows =>"5", :cols =>"80" } %>
<% end %>
<% end %>