Rails:摆脱泛型"X无效"验证错误

aar*_*ona 8 validation ruby-on-rails nested-attributes

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

我的层次结构是这样的:

class User < ActiveRecord::Base
  acts_as_authentic
  belongs_to :user_role, :polymorphic => true
end

class Customer < ActiveRecord::Base
  has_one :user, :as => :user_role, :dependent => :destroy
  accepts_nested_attributes_for :user, :allow_destroy => true
  validates_associated :user
end

class Employee < ActiveRecord::Base
  has_one :user, :as => :user_role, :dependent => :destroy
  accepts_nested_attributes_for :user, :allow_destroy => true
  validates_associated :user
end
Run Code Online (Sandbox Code Playgroud)

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

user.login can't be blank
User is invalid
customer.whatever is blah blah blah...etc
customer.some_other_error etc etc
Run Code Online (Sandbox Code Playgroud)

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

aar*_*ona 6

萨利尔的答案几乎是正确的,但他从来没有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
Run Code Online (Sandbox Code Playgroud)