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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- c# – 哪个更好?在存储库或域级服务(通过IQueryable或其他
- jsonp —— 跨域请求遇到的问题,服务接口返回View 对象才成
- 正则表达式在Java中没有明显的最大长度
- objective-c – containerURLForSecurityApplicationGroupI
- c# – BigInteger是否不可变?
- c# – 在一个强类型的世界中,为什么ASP.NET MVC对命名约定的
- react-native试玩(18)-开关控件
- cocos2d-x游戏开发系列教程-中国象棋03-主界面
- [Swift]LeetCode724. 寻找数组的中心索引 | Find Pivot Ind
- c# – Asp.Net MVC表单,具有未知的Controller参数