0

我有一个类似于下面的设置。一切正常,但是如果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
4

3 回答 3

1

不要调用employee.update_attributes(attributes),而是使用employee.update_attributes!(attributes)。(注意方法名称末尾的 bang。)这样,如果任何员工无效,就会引发异常。

现在,无论您在何处调用该自定义设置器,请务必将其包装在事务中,并拯救 ActiveRecord::RecordInvalid。然后,如果任何员工无效,整个事务将被回滚,您将有机会优雅地处理将验证错误传递回用户。

于 2013-05-08T18:48:45.737 回答
0

您可以声明validates_associated验证来实现这一点。

于 2013-05-08T18:02:14.793 回答
0

正如 ck3g 所指出的,您应该使用validates_associated验证子对象的方法。这个答案有一个例子。

Rails 还有一个钩子,可以通过一个调用(例如@employer.save)来保存您的父对象和子对象:accepts_nested_attributes_for

于 2013-05-08T20:49:41.367 回答