我们有葡萄API但我想知道我们是否可以在每次请求时用活动记录事务包装它。
在活动记录中进行交易,我们可以这样做:
ActiveRecord::Base.transaction do
# do select
# do update
# do insert
end
如何将其包装到葡萄API中?
据我所知,在Grape API中,我们可以在方法之前实现,在方法之后实现。
class API < Grape::API
before do
# ????? Need to implement code here to begin active record transaction
# this suppose to begin active record transaction
end
after do
# ????? Need to implement code here to end active record transaction
# this suppose to end active record transaction
end
end
答案 0 :(得分:3)
查看活动记录中transaction
块的implementation,您应该执行以下操作:
class API < Grape::API
before do
ActiveRecord::Base.connection.begin_transaction
end
after do
begin
ActiveRecord::Base.connection.commit_transaction unless @error
rescue Exception
ActiveRecord::Base.connection.rollback_transaction
raise
end
end
rescue_from :all do |e|
@error = e
ActiveRecord::Base.connection.rollback_transaction
# handle exception...
end
end