ruby - Rails form validation for custom setter during update_attributes? -


i have setup similar below. works fine, if validations in employee model fail (when custom setter invoked), how them fire when update_attributes called on employer model?

views/employers/_form.html.erb

<%= form_for @employer %>     <% @employer.employees.each |employee| %>         <%= fields_for "employer[employee_attributes][]", employee |e| %>             # form here         <% end %>     <% end %> <% end %> 

model/employer.rb

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 

solution:

as per sockmonks answer below call employee.update_attributes!(attributes) instead (with bang @ end). raises exception.

then in employer controller

controllers/employers_controller.rb

def update     @employer = employer.find(:id)     begin         @employer.update_attributes(params[:employer])     rescue activerecord::recordinvalid => e         # handle error(s)     end end 

instead of calling employee.update_attributes(attributes), use employee.update_attributes!(attributes) instead. (note bang @ end of method name.) way if employee invalid, exception raised.

now whereever you're calling custom setter, sure wrap in transaction, , rescue activerecord::recordinvalid. if employees invalid, whole transaction rolled back, , you'll have chance gracefully handle passing validation errors user.


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -