CodexBloom - Programming Q&A Platform

How to configure custom scenarios messages for ActiveModel validations in Rails 7 with multiple locales?

👀 Views: 35 💬 Answers: 1 📅 Created: 2025-06-02
ruby-on-rails i18n activemodel Ruby

Hey everyone, I'm running into an issue that's driving me crazy. I'm currently working on a Rails 7 application that supports multiple languages, and I'm having trouble setting up custom behavior messages for ActiveModel validations based on the user's locale. I've already configured the locale files for English and Spanish in `config/locales/en.yml` and `config/locales/es.yml`, but the custom behavior messages aren't showing up as expected. Here's a snippet of my `User` model where I define some validations: ```ruby class User < ApplicationRecord validates :email, presence: { message: I18n.t('errors.messages.email.blank') } validates :password, length: { minimum: 6, message: I18n.t('errors.messages.password.too_short') } end ``` In the locale files, I have: **config/locales/en.yml**: ```yaml en: errors: messages: email: blank: "Email need to be blank" password: too_short: "Password is too short (minimum is 6 characters)" ``` **config/locales/es.yml**: ```yaml es: errors: messages: email: blank: "El correo no puede estar vacío" password: too_short: "La contraseña es demasiado corta (mínimo 6 caracteres)" ``` Despite this setup, when I try to create a user without an email or a password shorter than 6 characters, I consistently see the default behavior messages instead of my custom ones. I've double-checked that I am correctly switching locales in my application using `I18n.locale = :es` when the user selects Spanish. Additionally, I can verify that `I18n.t('errors.messages.email.blank')` correctly returns the Spanish message in the Rails console when I test it. I've also tried using the `errors.add` method in a custom validation method, but I still face the same scenario where the default messages are appearing instead. Is there something I'm missing in the way ActiveModel handles locale-based custom behavior messages? Any guidance on how to resolve this would be greatly appreciated! This is part of a larger service I'm building. Has anyone else encountered this?