我有: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
,我可以看到表单页面上的错误。问题是该对象已保存到数据库中。
如果仍然存在相关错误,如何防止保存对象?
答案 0 :(得分:6)
您可以引发ActiveRecord :: RecordInvalid异常,它将阻止模型被保存并且不会破坏保存流。
if error?
errors[:base] << "error"
raise ActiveRecord::RecordInvalid.new(self)
end
答案 1 :(得分: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
依旧......