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

时间:2010-06-01 05:00:37

标签: ruby-on-rails validation 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

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

使用 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