模型中某些操作的验证

Smo*_*oke 3 validation ruby-on-rails

我遇到了一个我以前从未遇到过的问题.我正在研究由另一个程序员编写的代码,这有点乱.

这是问题所在.我在我的模型中有以下验证:

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
Run Code Online (Sandbox Code Playgroud)

我对这个控制器有两个动作.一个是new另一个是redeem.我希望通过操作执行所有这些验证,new但希望跳过大部分redeem操作.

我现在面临的问题是valid?在控制器中使用也验证了redeem行动不需要的东西.

我怎么能绕过这个?

rub*_*olo 14

这很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
Run Code Online (Sandbox Code Playgroud)

然后在其他地方(例如你的控制器),你可以这样做:

@whatever = Whatever.new(...)
@whatever.save  # <= will only run the first validation

@whatever.enable_strict_validation = true
@whatever.save  # <= will run both validations
Run Code Online (Sandbox Code Playgroud)

  • 要提出一个小问题,上面的示例将始终验证:name.如果没有:if参数,那些不经常验证的属性不应出现在验证中.此外,为了提高可读性,OP可以在一次验证中包含多个:属性,例如validate_presence_of:name1,:name2,:name3等 (2认同)