2012-06-02 1 views
1

:before_create 메서드를 사용하여 확인을 수행하고 false 또는 true을 반환하는 메서드가 있습니다. 이 방법은 false 또는 nil을 반환하는 경우false 또는 nil 일 때 before_create 메서드가 저장되지 않도록합니다.

def create_subscription_on_gateway 
    gateway = self.keyword.shortcode.provider 
    create_subscription = gateway.classify.constantize.new.create_subscription(self.phone,self.keyword_keyword,self.shortcode_shortcode,self.country) 
    errors[:base] << "An error has occurred when finding gateway." if gateway.nil? 
    errors[:base] << "No gateway found for this shortcode." if create_subscription.nil? 
    errors[:base] << "Subscription could not be made." if create_subscription == false 
end 

지금, 나는 괜찮 양식 페이지에 오류를 볼 수 있습니다. 문제는 개체가 데이터베이스에 저장되었다는 것입니다.

오류가 여전히 관련되어있을 때 개체를 저장하지 못하게하려면 어떻게해야합니까?

답변

5

어쨌든 before_create 대신 유효성 검사를 사용합니다. 그리고 다음이 저장되는 모델을 방지하고 흐름 저장 중단하지 않을 것이다,

6

당신은 액티브 :: RecordInvalid 예외를 올릴 수 ... before_validation

validate :gateway_presence 
validate :gateway_found 
validate :create_subscription 

def gateway_presence 
    if # ...your code here 
    errors.add(:gateway, "An error has occured..." 
    end 
end 

def gateway_found 
    if # ...your code here 
    errors.add(:gateway, "An error has occured..." 
    end 
end 

등으로 create_subscription_on_gateway을 변경합니다.

if error? 
errors[:base] << "error"  
raise ActiveRecord::RecordInvalid.new(self) 
end 
관련 문제