【问题标题】:Rails - validation ignores conditionRails - 验证忽略条件
【发布时间】:2013-09-10 12:53:57
【问题描述】:

我有这两个验证规则:

  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

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

我也尝试过这样做:

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

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

【问题讨论】:

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


    【解决方案1】:

    您使用了hidden_field_tag,因此您设置了params[:validate_step] 而不是params[:user][:validate_step]。因此,该值永远不会出现在您的模型中,因此 step_two 将始终返回 false。

    你应该使用

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

    【讨论】:

    • 哦,多么愚蠢的错误...谢谢弗雷德里克。还有一件事 - 我现在可以使用实时验证吗?因为它目前不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    相关资源
    最近更新 更多