Rails - 验证忽略条件

时间:2013-09-06 12:07:04

标签: ruby-on-rails ruby validation model conditional-statements

我有两个验证规则:

  attr_accessor :validate_step
  validates :full_name, :presence => {:message => 'Full Name cannot be blank.'}, :allow_blank => true, :length => {:minimum => 3, :maximum => 50}, :if => :step_two?
  validates :birthdate, :presence => {:message => 'Birthdate cannot be blank.'}, :if => :step_two?

  def step_two?
    validate_step == 'two'
  end

以下是表格:

= form_for @user, :validate => true do |f|
  = hidden_field_tag :validate_step, 'two'
  .control-group
    = f.label 'Full Name'
    = f.text_field :full_name
  .control-group
    = f.label 'Birthdate'
    = f.text_field :birthdate

这是表格的第二步。当我将这两个字段留空时,保存了evertyhing,我没有看到预期的验证错误。

我也尝试过这样的事情:

  validates :full_name, :presence => {:message => 'Full Name cannot be blank.'}, :allow_blank => true, :length => {:minimum => 3, :maximum => 50}, :if => Proc.new { |user| user.validate_step == 'two' }
  validates :birthdate, :presence => {:message => 'Birthdate cannot be blank.'}, :if => Proc.new { |user| user.validate_step == 'two' }

但结果是一样的,我没有看到验证错误 - 我做错了什么?

1 个答案:

答案 0 :(得分:1)

您已使用hidden_field_tag,因此导致设置params[:validate_step]而不是params[:user][:validate_step]。因此,该值永远不会影响您的模型,因此step_two将始终返回false。

相反,你应该使用

f.hidden_field :validate_step, :value => 'two'