title: Rails form validation for custom setter during update_attributes?
body: <p>I have a setup similar to below. Everything works fine, but if the validations in the <code>Employee</code> model fail (when the custom setter is invoked), how do I get them to fire when <code>update_attributes</code> is called on the <code>Employer</code> model?</p>
  
  <h3>views/employers/_form.html.erb</h3>
  
  <pre><code>&lt;%= form_for @employer %&gt;
      &lt;% @employer.employees.each do |employee| %&gt;
          &lt;%= fields_for "employer[employee_attributes][]", employee do |e| %&gt;
              # FORM HERE
          &lt;% end %&gt;
      &lt;% end %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <h3>model/employer.rb</h3>
  
  <pre><code>attr_accessible :employee_attributes
  has_many :employees
  
  def employee_attributes=(employee_attributes)
      employee_attributes.each_pair{|id,attributes|
          employee = Employee.find(id)
          employee.update_attributes(attributes)
      }
  end
  </code></pre>
  
  <h2>Solution:</h2>
  
  <p>As per sockmonks answer below call <code>employee.update_attributes!(attributes)</code> instead (with the bang at the end). This raises an exception.</p>
  
  <p>Then in <code>Employer</code> controller</p>
  
  <h3>controllers/employers_controller.rb</h3>
  
  <pre><code>def update
      @employer = Employer.find(:id)
      begin
          @employer.update_attributes(params[:employer])
      rescue ActiveRecord::RecordInvalid =&gt; e
          # Handle Error(s)
      end
  end
  </code></pre>