Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3 with composed_of model and validation
    primarykey
    data
    text
    <p>I have this domain model:</p> <pre><code>class Person &lt; 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 &amp;&amp; city == other_address.city &amp;&amp; zip_code == other_address.zip_code &amp;&amp; country == other_address.country end def persisted? false end end </code></pre> <p>When I try to save an invalid model:</p> <pre><code>&gt; p = Person.new =&gt; #&lt;Person id: nil, name: nil, surname: nil, address_street: nil, address_city: nil, address_zip_code: nil, address_country: nil &gt; p.valid? =&gt; false &gt; p.errors =&gt; {:name=&gt;["can't be blank"], :surname=&gt;["can't be blank"], :address=&gt;["is invalid"]} </code></pre> <p>This is ok, but I would prefer to have the error array filled with the error messages of Address, like this:</p> <pre><code>=&gt; {:name=&gt;["can't be blank"], :surname=&gt;["can't be blank"], :address_street=&gt;["can't be blank"], :address_city=&gt;["can't be blank"], :address_zip_code=&gt;["can't be blank"], :address_country=&gt;["can't be blank"]} </code></pre> <p>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?</p> <p>Thank you very much.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload