8

我有一个注册表单,其中包含您想要调用的任何嵌套关联/属性。

我的层次结构是这样的:

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

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

4

2 回答 2

6

Salil 的回答几乎是正确的,但他从未做到 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
于 2010-09-14T08:39:39.293 回答
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

已编辑

笔记:-

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

%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
于 2010-06-01T05:26:35.523 回答