2011-04-08 69 views
3

我有一個用戶模式是這樣的:的Rails void驗證防止保存

class User < ActiveRecord::Base 
    validates :password, :presence => true, 
         :confirmation => true, 
         :length => { :within => 6..40 } 
    . 
    . 
    . 
end 

用戶模型中,我有一個BILLING_ID專欄中,我要保存到從OrdersController它看起來像這樣:

class OrdersController < ApplicationController 
    . 
    . 
    . 
    def create 
     @order = Order.new(params[:order]) 
     if @order.save 
      if @order.purchase 
       response = GATEWAY.store(credit_card, options) 
       result = response.params['billingid'] 
       @thisuser = User.find(current_user) 
       @thisuser.billing_id = result 
       if @thisuser.save 
         redirect_to(root_url), :notice => 'billing id saved') 
        else 
         redirect_to(root_url), :notice => @thisuser.errors) 
        end 
      end 
     end 
    end 

由於用戶模型中的validates :password@thisuser.save未保存。但是,一旦我評論驗證,@thisuser.save返回true。對我來說這是一個陌生的領域,因爲我認爲這個驗證只在創建一個新用戶時才起作用。有人可以告訴我,如果validates :password每次嘗試保存在用戶模型中都應該啓動嗎?謝謝

回答

12

您需要指定何時運行驗證,否則它們將在每個save調用中運行。這是很容易限制,但:

validates :password, 
    :presence => true, 
    :confirmation => true, 
    :length => { :within => 6..40 }, 
    :on => :create 

另一種選擇是有條件此驗證觸發:

validates :password, 
    :presence => true, 
    :confirmation => true, 
    :length => { :within => 6..40 }, 
    :if => :password_required? 

您可以定義是否需要密碼,在此之前的模型可以被認爲是有效的指示的方法:

class User < ActiveRecord::Base 
    def password_required? 
    # Validation required if this is a new record or the password is being 
    # updated. 
    self.new_record? or self.password? 
    end 
end 
+0

太棒了。謝謝塔德曼。我非常感謝 – railslearner 2011-04-08 20:33:30

0

很可能是因爲您要驗證密碼已經被證實(:confirmation => true),但password_confirmation確實 不存在。

你可以打破這種出像:

validates_presence_of :password, :length => { :within => 6..40 } 
validates_presence_of :password_confirmation, :if => :password_changed? 

我喜歡這種方法,因爲如果用戶發生了改變,他們的密碼,它會要求用戶輸入了相同的password_confirmation。

+0

謝謝Jesse,這非常有用 – railslearner 2011-04-08 22:58:20