加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:摆脱泛型“X无效”验证错误

发布时间:2020-12-16 19:02:34 所属栏目:百科 来源:网络整理
导读:我有一个注册表单,它具有嵌套的关联/属性,无论你想要什么. 我的层次结构是这样的: class User ActiveRecord::Base acts_as_authentic belongs_to :user_role,:polymorphic = trueendclass Customer ActiveRecord::Base has_one :user,:as = :user_role,:dep
我有一个注册表单,它具有嵌套的关联/属性,无论你想要什么.

我的层次结构是这样的:

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,: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无效”消息.这让我的客户感到困惑,所以我想知道是否有一种快速的方法可以做到这一点,而不必自己提交错误.

解决方法

萨利尔的答案几乎是正确的,但他从来没有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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读