ruby-on-rails – 对模型中某些操作的验证
发布时间:2020-12-17 01:52:18 所属栏目:百科 来源:网络整理
导读:我遇到了一个我以前从未遇到过的问题.我正在研究由另一个程序员编写的代码,这有点乱. 这是问题所在.我在我的模型中有以下验证: validates_presence_of :subscription_level,:message = 'please make a selection'validates_presence_of :shipping_first_nam
我遇到了一个我以前从未遇到过的问题.我正在研究由另一个程序员编写的代码,这有点乱.
这是问题所在.我在我的模型中有以下验证: validates_presence_of :subscription_level,:message => 'please make a selection' validates_presence_of :shipping_first_name validates_presence_of :shipping_last_name validates_presence_of :shipping_address validates_presence_of :shipping_city validates_presence_of :shipping_state validates_presence_of :shipping_postal_code validates_presence_of :shipping_country validates_presence_of :billing_first_name validates_presence_of :billing_last_name validates_presence_of :billing_address validates_presence_of :billing_city validates_presence_of :billing_state validates_presence_of :billing_postal_code validates_presence_of :billing_country validates_presence_of :card_number validates_numericality_of :card_number validates_presence_of :card_expiration_month validates_numericality_of :card_expiration_month validates_presence_of :card_expiration_year validates_numericality_of :card_expiration_year validates_presence_of :card_cvv validates_numericality_of :card_cvv 我对这个控制器有两个动作.一个是新的,另一个是赎回. 我现在面临的问题是使用有效吗?在控制器中也验证了兑换操作不需要的东西. 我怎么能绕过这个? 解决方法
这很hacky,但我不得不求助于一个属性标志,可以在某些状态启用/禁用验证. (我的具体示例是一个多页面表单,我们最终要验证对象的所有必填字段,但我们只能验证先前页面上提交的数据)
这是一个如何看起来的例子: class Whatever < ActiveRecord::Base attr_accessor :enable_strict_validation validates_presence_of :name # this always happens validates_uniqueness_of :name,:if => :enable_strict_validation end 然后在其他地方(例如你的控制器),你可以这样做: @whatever = Whatever.new(...) @whatever.save # <= will only run the first validation @whatever.enable_strict_validation = true @whatever.save # <= will run both validations (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |