2011-04-08 4 views
3

을 방지 저장 :레일의 유효성을 검사 나는이 같은 사용자 모델이

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 
: 사용자 모델에서
class User < ActiveRecord::Base 
    validates :password, :presence => true, 
         :confirmation => true, 
         :length => { :within => 6..40 } 
    . 
    . 
    . 
end 

, 나는 나는이처럼 보이는 OrdersController가에서로 저장할 BILLING_ID 열이를

사용자 모델이 validates :password이므로 @thisuser.save은 저장되지 않습니다. 그러나 일단 유효성 검증을 주석 처리하면 @thisuser.save이 true를 리턴합니다. 이 유효성 검사는 새 사용자를 만들 때만 작동한다고 생각했기 때문에 이것은 나에게 익숙하지 않은 영역입니다. 누군가 사용자 모델에 저장하려고 할 때마다 validates :password이 실행되어야한다고 말 할 수 있습니까? 감사합니다

답변

12

유효성 검사를 실행할 시간을 지정해야합니다. 그렇지 않으면 모든 save 호출에서 실행됩니다. 하지만 이것은 제한하기 쉽습니다 :

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

당신은이 모델이 유효한 것으로 간주되기 전에 암호가 필요한 경우를 나타내는 방법을 정의

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

대안은 조건이 검증 트리거를하는 것입니다 :

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

굉장합니다. 고마워요, Tadman. 정말 고마워. – railslearner

0

암호가 (:confirmation => true를) 확인 된 것으로 검증되어 있기 때문에 가능성이 높습니다하지만 password_confirmation는 않습니다 존재하지 않는다.

당신은 같은이를 깰 수 :

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

나는이 방법을 좋아하는 사용자가 지금까지 자신의 암호를 변경하는 경우, 그것은 사용자가 동일한 password_confirmation를 입력 필요하기 때문이다.

+0

제시. 고마워,이게 굉장히 유용하다. – railslearner

관련 문제