1

有人可以向我解释为什么它似乎忽略了此代码中的 with_options 块吗?

class User < ActiveRecord::Base
  attr_accessible :name,:user_type,:policy_num,:address,:city,:state,:zip,:phone,:fax,:email,
                :password, :password_confirmation
has_secure_password
has_many :policies
has_many :dealer_forms

before_save {|user| user.email = email.downcase}
before_save :create_remember_token

ZIP_REGEX = /^\d{5}(-\d{4})?$/
EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
COMPLEX_PHONE_REGEX = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/

validates :name, presence: true, length:{in:4..50}
validates :email, presence: true, uniqueness: {case_sensitive: false},format:{with:EMAIL_REGEX}
validates :password, length:{in:6..20}, if: :password
validates :password_confirmation, presence:true, if: :password
validates :user_type, presence: true, inclusion: {in: %w(Dealer Producer System)}

# Validate True User items skip admin users #
with_options :unless => :is_system_user? do |u|
  u.validates :policy_num, presence: true
  u.validates :address, presence: true
  u.validates :city, presence: true
  u.validates :state, presence: true, length:{is: 2} 
  u.validates :zip, presence: true, format:{with:ZIP_REGEX,message: "Not a valid Zip Code"}
  u.validates :phone, allow_blank: true, format:{with:COMPLEX_PHONE_REGEX}
  u.validates :fax, allow_blank: true, format:{with:COMPLEX_PHONE_REGEX}
end

private
  def create_remember_token
    self.remember_token = SecureRandom.urlsafe_base64
  end
  def is_system_user?
    user_type == "System" ? true : false
  end
end

我尝试了以下方法:

with_options unless: :is_system_user?
with_options unless: Proc.new{|user| user.user_type == "System"}
with_options unless:"user_type = 'System'"
with_options if: "user_type != 'System'"

但由于某种原因,当我尝试在控制台中创建用户时,它仍然在块内运行验证。

任何帮助将不胜感激。谢谢

4

0 回答 0