0

我有这两个验证规则:

  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

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

我也尝试过这样做:

  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' }

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

4

1 回答 1

1

你已经使用hidden_field_tag了,所以你导致params[:validate_step]被设置而不是params[:user][:validate_step]. 结果,该值永远不会进入您的模型,因此step_two将始终返回 false。

相反,您应该使用

f.hidden_field :validate_step, :value => 'two'
于 2013-09-06T12:16:25.917 回答