ActiveModel的条件验证

时间:2014-11-13 15:41:59

标签: ruby-on-rails ruby

我有一种情况需要验证一个方法的某些字段和另一个方法的所有字段。

这就是我的模型当前的样子:

class User < ActiveInteraction::Base

def initialize
  full_validation = true
end

# All user related auth data
string :email
string :password
string :name
string :surname
string :phone

@error
@full_validation
attr_accessor :error, :full_validation

# Validation rules
validates :email,
  presence: true,
  format: {
    with: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
    :multiline => true
  }

validates :password, presence: true, length: { minimum: 6 }

validates :name, presence: true,
  format: {
    with: /^[a-zA-Z\d\s]*$/,
    :multiline => true
  }, :if => :full_validation?

validates :surname, presence: true,
  format: {
    with: /^[a-zA-Z\d\s]*$/,
    :multiline => true
  }, :if => :full_validation?

validates :phone, presence: true, :if => :full_validation?

如果我拨打user = User.new然后拨打user.full_validation = false,则只应验证电子邮件和密码字段,但验证名称,姓氏和电话中的if语句完全忽略此项并返回验证错误。< / p>

我也尝试过其他几种方法都可以工作(没有错误),但仍然验证所有字段:

def isFullValidation
  full_validation == true
end

我还尝试使用with_options并在if: :full_validation? do .. end语句中包含3个验证规则。

1 个答案:

答案 0 :(得分:1)

尝试使用分组条件验证

with_options if: Proc.new { |u| u.is_full_validation? } do |user|
  user.validates ... # pay attention to the 'user.' in front of each validation!!
  user.validates ...
end

def is_full_validation?
  full_validation == true
end