1

我有一个:before_create方法可以执行一些检查并返回falseor 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 回答