Rails:摆脱generics“X无效”validation错误

我有一个注册表单,它具有嵌套的关联/属性,无论你想要什么。

我的层次结构是这样的:

class User  true end class Customer  :user_role, :dependent => :destroy accepts_nested_attributes_for :user, :allow_destroy => true validates_associated :user end class Employee  :user_role, :dependent => :destroy accepts_nested_attributes_for :user, :allow_destroy => true validates_associated :user end 

我在这些课程中也有一些validation内容。 我的问题是,如果我尝试使用空白表单创建和客户(或员工等),我会得到所有的validation错误,加上一些通用的错误,如“用户无效”和“客户无效”如果我迭代错误我得到的东西:

 user.login can't be blank User is invalid customer.whatever is blah blah blah...etc customer.some_other_error etc etc 

由于嵌套用户模型中至少有一个无效字段,因此会在错误列表中添加额外的“X无效”消息。 这让我的客户感到困惑,所以我想知道是否有一种快速的方法可以做到这一点,而不必自己提交错误。

萨利尔的答案几乎是正确的,但他从来没有100%做到。 这是正确的方法:

 def after_validation # Skip errors that won't be useful to the end user filtered_errors = self.errors.reject{ |err| %{ person }.include?(err.first) } # recollect the field names and retitlize them # this was I won't be getting 'user.person.first_name' and instead I'll get # 'First name' filtered_errors.collect{ |err| if err[0] =~ /(.+\.)?(.+)$/ err[0] = $2.titleize end err } # reset the errors collection and repopulate it with the filtered errors. self.errors.clear filtered_errors.each { |err| self.errors.add(*err) } end 

使用after_validation方法

  def after_validation # Skip errors that won't be useful to the end user filtered_errors = self.errors.reject{ |err| %w{ user User }.include?(err.first) } self.errors.clear filtered_errors.each { |err| self.errors.add(*err) } end 

EDITED

注意:-

在您的情况下添加以下列表是用户或用户。 如果您有多个以空格分隔的assosciation,则可以添加多个。

 %w{ User user }.include?(err.first) #### This piece of code from the above method has logic which reject the errors which won't be useful to the end user