MaxZXL MaxZXL - 1 year ago 114
Ruby Question

Rails model using only default locale

  • I have a model with custom validations. I return the validation
    errors to the view as JSON using AJAX.

  • I need to show the error
    messages with the right locale but the messages
    show in English (default) for each locale.

  • When I return I18n.locale
    itself instead of the message (for troubleshooting) it shows "en" no matter what is the set locale.

  • I18n in controllers or views works as expected, this problem
    occurs only in the model.

  • The only configuration that I've made regarding locale is setting the default locale in the application config and setting the locale before each action in the application controller.

  • Another thing that I've noticed is that when I use root_path without providing the locale, it's using the default locale instead keeping the current locale like it should. I think those issues are connected


  • When I print the locale parameter in controller#create, I get nil. For some reason I don't have the locale parameter at all.

model file:

validate :relevant_date_time

def relevant_date_time
errors.add(:date_error, I18n.t("validations.date_error")) unless date_time_is_relevant?


before_action :set_locale

def set_locale
I18n.locale = params[:locale] || I18n.default_locale

Am I forgetting something?

Information I reviewed:

Answer Source

Solved by adding the following method in application controller:

  def default_url_options(options={})
    { locale: I18n.locale }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download