Rails:摆脱通用的"X无效"验证错误 [英] Rails: Getting rid of generic "X is invalid" validation errors

查看:69
本文介绍了Rails:摆脱通用的"X无效"验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个注册表格,其中包含嵌套的关联/属性,只要您想称呼它们即可.

I have a sign-up form that has nested associations/attributes whatever you want to call them.

我的层次结构是这样:

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

这些类中也有一些验证内容.我的问题是,如果我尝试使用空白表格创建和客户(或员工等),则会收到所有验证错误,我应该得到一些通用错误,例如用户无效"和客户无效".我得到类似的错误:

I have some validation stuff in these classes as well. My problem is that if I try to create and Customer (or Employee etc) with a blank form I get all of the validation errors I should get plus some Generic ones like "User is invalid" and "Customer is invalid" If I iterate through the errors I get something like:

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

由于在嵌套用户模型中至少有一个无效字段,因此将额外的"X无效"消息添加到错误列表中.这使我的客户感到困惑,所以我想知道是否有一种快速的方法来执行此操作,而不必自己解决错误.

Since there is at least one invalid field in the nested User model, an extra "X is invalid" message is added to the list of errors. This gets confusing to my client and so I'm wondering if there is a quick way to do this instead of having to filer through the errors myself.

推荐答案

Salil的回答几乎是正确的,但他从未做到100%.这是正确的方法:

Salil's answer was almost right but he never made it 100%. Here is the correct way to do it:

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

这篇关于Rails:摆脱通用的"X无效"验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆