我有一个
: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
我可以在表单页面上看到错误。问题是该对象已保存到数据库中。
当对象仍然存在关联错误时,如何防止对象被保存?
您可以引发 ActiveRecord::RecordInvalid 异常,它将阻止保存模型并且不会中断保存流程。
if error?
errors[:base] << "error"
raise ActiveRecord::RecordInvalid.new(self)
end
不如使用验证来代替 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
等等...
在 before_create 上你可以这样做:
def before_create_func
errors.add(:base, "error message")
throw :abort
end
这会添加错误并阻止记录保存。