I have this domain model:
class Person < ActiveRecord::Base composed_of :address, mapping: [%w(address_street street), %w(address_city city), %w(address_zip_code zip_code), %w(address_country country)] validates :name, presence: true, length: { maximum: 50 } validates :surname, presence: true, length: { maximum: 50 } validates_associated :address end class Address include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming attr_reader :street, :city, :zip_code, :country validates :street, presence: true validates :city, presence: true validates :zip_code, presence: true validates :country, presence: true def initialize(street, city, zip_code, country) @street, @city, @zip_code, @country = street, city, zip_code, country end def ==(other_address) street == other_address.street && city == other_address.city && zip_code == other_address.zip_code && country == other_address.country end def persisted? false end end
When I try to save an invalid model:
> p = Person.new => #<Person id: nil, name: nil, surname: nil, address_street: nil, address_city: nil, address_zip_code: nil, address_country: nil > p.valid? => false > p.errors => {:name=>["can't be blank"], :surname=>["can't be blank"], :address=>["is invalid"]}
This is ok, but I would prefer to have the error array filled with the error messages of Address, like this:
=> {:name=>["can't be blank"], :surname=>["can't be blank"], :address_street=>["can't be blank"], :address_city=>["can't be blank"], :address_zip_code=>["can't be blank"], :address_country=>["can't be blank"]}
The question is: is there a clean Rails way to do it? Or simply I have to move the validation code from Address to Person (pretty ugly)? Any other solution?
Thank you very much.