1

:before_createいくつかのチェックとリターンfalseまたはを実行するメソッドがありますtrue

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

これで、メソッドが返さfalseれるかnil、フォームページにエラーが表示されれば問題ありません。問題は、オブジェクトがデータベースに保存されていることです。

エラーがまだ関連付けられているときにオブジェクトが保存されないようにするにはどうすればよいですか?

4

2 に答える 2

7

ActiveRecord::RecordInvalid 例外を発生させることができます。これにより、モデルが保存されなくなり、保存フローが中断されなくなります。

if error?
 errors[:base] << "error"    
 raise ActiveRecord::RecordInvalid.new(self)
end
于 2014-01-06T15:18:04.050 に答える
5

before_create の代わりにバリデーションを使用するのはどうですか。そして、 create_subscription_on_gateway を 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 

等々...

于 2012-06-02T23:32:36.350 に答える