CodexBloom - Programming Q&A Platform

How to handle custom scenarios messages in ActiveModel validations without duplicating code?

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-03
ruby rails activemodel validations

I'm relatively new to this, so bear with me. I'm having a hard time understanding I'm trying to configure I'm stuck on something that should probably be simple... I'm currently working on a Rails 6 application and I've defined several models with custom validations using ActiveModel. However, I'm working with a scenario in how to efficiently manage custom behavior messages without duplicating code across different models. For instance, I have a `User` model and a `Profile` model where both require a unique email address. Right now, I'm including the validation like this: ```ruby class User < ApplicationRecord validates :email, uniqueness: { message: 'has already been taken' } end class Profile < ApplicationRecord validates :email, uniqueness: { message: 'has already been taken' } end ``` The scenario is that if I need to change that message in the future, I have to update it in multiple places. I tried using a concern to share the validation logic, but I ran into issues with the behavior messages not being scoped correctly. Here’s what I attempted: ```ruby module EmailValidatable extend ActiveSupport::Concern included do validates :email, uniqueness: { message: 'has already been taken' } end end class User < ApplicationRecord include EmailValidatable end class Profile < ApplicationRecord include EmailValidatable end ``` This approach throws an behavior related to the validation not being properly defined when I run my tests. Is there a recommended way to define custom validations for multiple models without repeating behavior messages, or do I need to create a custom validator? Any examples would be greatly appreciated! This is part of a larger web app I'm building. Am I missing something obvious? This issue appeared after updating to Ruby 3.10. I'm developing on macOS with Ruby. What would be the recommended way to handle this? Thanks for your help in advance!