1

I am building a car rental app with Ruby on Rails and currently I have been coding with English. Basically I have an user and car model, where user can login, sign in, log out and list their car.

I would like to implement another language allowing the user to select English or Spanish from a dropdown. I have default error messages returns from the controller actions such as "can't be blank, already used" etc. And I also have custom JS messages, such as if user successfully adds a car, jQuery returns "your car has been published". Lastly, I also have Flash messages. But I do not know how should I handle errors, custom JS and Flash messages in the YML file according to user's language selection.

Laurel
  • 5,965
  • 14
  • 31
  • 57
Shalafister's
  • 761
  • 1
  • 7
  • 34

2 Answers2

0

It actually really depends on the structure of your YAML file, for example, for ActiveRecord error messages:

it:
  errors:
    format: "%{attribute} %{message}"

    messages: &errors_messages
      empty: "non può essere vuoto"
      blank: "non può essere lasciato in bianco"

If you want to access I18n (a.k.a Internationalization) outside of views, you can use I18n.t(your_key), which is in fact the helper you have access to in your views. So for example, if you wish to translate a notice in a controller you could be doing something like:

def your_action
  redirect_to other_path, notice: I18n.t("notices.successful_action")
end

And then having in your YAML the correspondent structure:

en:
  notices:
    successful_action: "You did it!"

Hope this helps!

Francesco Renzi
  • 547
  • 8
  • 14
0

I do not know how should I handle error, custom js and flash messages in yml file according to user's language selection

  • For Rails app-related translations in general, including error messages, the Rails i18n gem has you covered. You can see what languages have been translated in the gem's locale file.
  • For specifically overriding error messages or creating new ones, see The Rails Guide sections on looking up translations and translations for ActiveRecord models to see what keys in your YAML files you should be putting your translations under.
  • For flash messages, have a look at this StackOverflow question to see how you can use lazy lookups (eg t('.notice')) in your controllers.
  • For the ability to use translations in Javascript files in the same way you do in Ruby (eg I18n.t("my_translation"), and be able to manage those translations in your YAML files with the rest of your Rails translations, have a look at the i18n-js gem. Setup instructions are in the README file.
Community
  • 1
  • 1
Paul Fioravanti
  • 16,423
  • 7
  • 71
  • 122