Rails多条件验证

时间:2013-03-10 10:56:05

标签: ruby-on-rails ruby-on-rails-3

我有以下型号

class User < ActiveRecord::Base
  VALID_EMAIL_REGEX = /^.+@.+\..+$/i 
  attr_accessible :active_list_id, :password, :password_confirmation, :email, :temp
  has_secure_password
  before_create { generate_token(:auth_token) }
  if :temp.nil?
    before_validation :downcase_email
    validates_presence_of :email, :password, :password_confirmation, :on => :create
    validates_confirmation_of :password
    #something@something.something
    validates :email, :uniqueness => true, 
              :format => {:with => VALID_EMAIL_REGEX }
  end
  after_create { make_list([email,"'s shopping list"].join('')) }

  has_many :shopping_lists
  has_many :transactions, :class_name => 'Order'

  HUMANIZED_ATTRIBUTES = {
    :password_digest => "Password"
  }
  ...
end

我尝试通过调用User.create(:temp => true)(这是一个布尔值并在我的迁移/模式中定义)在我的rails控制台中创建模型。但它总是会回滚交易。我做错了什么?

我还尝试对所有3次验证进行:if => temp.nil?if => "temp.nil?"以及:if => lambda { |user| user.temp.nil? }

1 个答案:

答案 0 :(得分:0)

创建一个名为temp_is_nil的方法?并在if条件

上使用它
def temp_is_nil?
  temp.nil?
end

确保temp是用户的属性。

before_validation :downcase_email, if: temp_is_nil?
validates_presence_of :email, :password, :password_confirmation, :on => :create, if: temp_is_nil?
validates_confirmation_of :password, if: temp_is_nil?
validates :email, :uniqueness => true, 
          :format => {:with => VALID_EMAIL_REGEX }, if: temp_is_nil?