gpt4 book ai didi

ruby-on-rails - rails : Getting rid of generic "X is invalid" validation errors

转载 作者:行者123 更新时间:2023-12-04 07:29:39 26 4
gpt4 key购买 nike

我有一个注册表单,里面有嵌套的关联/属性,不管你想怎么称呼它们。

我的层次结构是这样的:

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

最佳答案

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

关于ruby-on-rails - rails : Getting rid of generic "X is invalid" validation errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2947365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com