我有一个类似于下面的设置。一切正常,但是如果Employee
模型中的验证失败(调用自定义设置器时),我如何让它们update_attributes
在模型上调用时触发Employer
?
意见/雇主/_form.html.erb
<%= form_for @employer %>
<% @employer.employees.each do |employee| %>
<%= fields_for "employer[employee_attributes][]", employee do |e| %>
# FORM HERE
<% end %>
<% end %>
<% end %>
模型/雇主.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
解决方案:
根据 sockmonks 的回答,employee.update_attributes!(attributes)
改为下面的电话(最后是一声巨响)。这引发了一个异常。
然后在Employer
控制器中
控制器/employers_controller.rb
def update
@employer = Employer.find(:id)
begin
@employer.update_attributes(params[:employer])
rescue ActiveRecord::RecordInvalid => e
# Handle Error(s)
end
end