Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You wil be surprised - it cannot work!</p> <p>Ok the reason can be found in the Rails code. First validation will run the code:</p> <pre><code># Validations module # Returns the Errors object that holds all information about # attribute error messages. def errors @errors ||= Errors.new(self) end </code></pre> <p>As it is a first run then it will create new instance of Errors class. Simple, isn't it? But there is a gotcha - the parameter is self. In your case it is "contact" object.</p> <p>Later then when you call this again on cloned object, the @errors instance will not be created again - as it is not null. And there it is! Instead of passing "cloned" self, the older self is used.</p> <p>Later in the validation code there the Errors class runs the code that read the value from @base which is the <em>self</em> from the initialization. Can you see it? The values for test are read from original model not from the clone! So the validation on "cloned" object runs on values from the original.</p> <p>Ok, so far for the "why not" and now a few words about "how to".</p> <p>The solution is simple - just set @errors to nil after cloning and before validation. As it is quite private, the simple assignment doesn't work. But this works:</p> <pre><code>cloned.instance_eval do @errors = nil end </code></pre> <p>And some tip for interesting reading: <a href="http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/" rel="nofollow">http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/</a></p> <p>It is quite comprehensive explanation how the validations in Rails 3 works.</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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