I have two model as follows
class User < ActiveRecord::Base
validates_associated :account
end
class Account < ActiveRecord::Base
belongs_to :user
#----------------------------------Validations--Start-------------------------
validates_length_of :unique_url, :within => 2..30 ,:message => "Should be atleast 3 characters long!"
validates_uniqueness_of :unique_url ,:message => "Already Taken"
validates_format_of :unique_url,:with => /^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])$/ , :message => " Cannot contain special charaters"
#----------------------------------Validations--End---------------------------
end
Now when I associate an account to a user it says
“Account is invalid”
Instead I want to get the error message directly from that model.
so it should say
"Should be atleast 3 characters long!" or "Already Taken" or " Cannot contain special charaters"
is there a way to do this ?
I don’t want to give a generic message like :
validates_associated :account , :message=>"one of the three validations failed"
You can write your own custom validator, based on the code for the built-in validator.
Looking up the source code for validates_associated, we see that it uses the "AssociatedValidator". The source code for that is:
So you can use this as an example to create a custom validator that bubbles error messages like this (for instance, add this code to an initializer in
config/initializers/associated_bubbling_validator.rb):So you can now validate like so:
Also, be sure to add a
validate: falsein yourhas_manyassociation, otherwise, Rails will validate the association by default and you’ll end up with two error messages, one given by your new AssociatedBubblingValidator and one generic given by Rails.