In this third article in a four-part series on adding support for multiple languages to a Ruby-on-Rails ecomerce application, you will learn how to add a translation to a site, edit the translation, and more. This article is excerpted from chapter 10 of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Translating a Site for Multiple Language Support (Page 1 of 5 )
Implementing the Add Translation User Story
Add the following code (showing the create action) to translate_controller.rb :
def create from = params[:view][:text] singular = params[:view][:singular_form] plural = params[:view][:plural_form] if(plural.empty? && !singular.empty? && !from.empty?) Locale.set_pluralized_translation(from, 1, singular) flash[:notice] = "Translated '#{from}' to '#{singular}'" elsif(!plural.empty? && !singular.empty? && !from.empty?) Locale.set_translation(from, Locale.language, singular, plural) flash[:notice] = ? "Translated '#{from}' to singular '#{singular}' and plural '#{plural}'" else flash[:notice] = ? "Please specify singular and/or plural form for the translation" end redirect_to :controller => 'translate', :action => 'index' end
The if clause checks if the user is entering a translation that has only a singular form, and then uses Locale.set_pluralized_translation to add the translation to the database. The first parameter is the base language text, the second parameter specifies that the text is in singular form ( 1 for singular and 0 for plural), and the last parameter specifies the translated text in singular form.
The elsif clause uses Locale.set_translation to add a new translation to the database, which has both singular and plural forms. The method’s first argument is the base language text, the second is the current locale, the third is the singular form, and the fourth is the plural form of the translated text.
The controller shows an error message if no text was entered in both the singular and text fields. At the end of the action, we redirect the user to the same translation list page.
Type “Next page” in the Text field and “Nästa sida” in the Singular form field, and then click Add translation. This time, it should succeed, and you should see the list showing the new translation at the top of the list, as shown in Figure 10-4.
You could now try to click the “Nästa sida” text, but the in-place editor would show an error message, because we haven’t created the action for it yet.
Figure 10-4.Translation view showing a list of translations