我有一个模型,我正在通过表单向导进行更新。在最后一步,我想用表单数据更新对象,然后在模型中调用回调以将数据推送到外部API。我遇到的问题是finall步骤是将数据保存在两个事务中。
# controller
def update
@business = current_user
@loanapplication = @business.loan_applications.last
@loanapplication.update_attributes(loan_application_params(step))
params[:loan_application][:status] = 'active' if step == steps.last
render_wizard @loanapplication
end
# Model
# Callbacks
after_commit :create_salesforce_loan_application, :on => :update
def create_salesforce_loan_application
if self.status == 'active'
puts "create salesforce function running"
# Updating business column
self.business.update_column(:state, 1)
end
end
数据库交易
[paperclip] saving XXX.xlsx
[AWS S3 200 0.101161 0 retries] put_object(:acl=>:public_read,:bucket_name=>"",:content_length=>29467,:content_type=>"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",:data=>Paperclip::UploadedFileAdapter: FX - Competitive Analysis.xlsx,:key=>"XX.xlsx")
(0.4ms) COMMIT
create salesforce function running
SQL (1.3ms) UPDATE "users" SET "state" = 1 WHERE "users"."type" IN ('Business') AND "users"."id" = 55
(0.2ms) BEGIN
(0.2ms) COMMIT
create salesforce function running
SQL (1.3ms) UPDATE "users" SET "state" = 1 WHERE "users"."type" IN ('Business') AND "users"."id" = 55
这两个提交正在我的模型中进行两次回调,如果我能弄清楚如何保存更新模型中的数据一次,那么我的回调只会触发一次。有没有办法可以找出造成两次提交的原因?
答案 0 :(得分:0)
:create_salesforce_loan_application
被调用两次,因为对象在此过程中更新了两次,可能是其他回调或宝石,如Paperclip。
更好的方法是使用after_save
代替after_commit
,检查:status
属性是否已更改。
class LoanApplication < ActiveRecord:Base
after_save :create_salesforce_loan_application, on: :update
def create_salesforce_loan_application
if status_changed? && status == 'active'
puts "create salesforce function running"
# Updating business column
business.update_column(:state, 1)
end
end
end