#59 Optimistic Locking

本文介绍了一种通过乐观锁机制解决两个用户几乎同时尝试更新同一记录时出现的数据覆盖问题。通过在产品模型中增加锁版本字段并进行相应控制器修改,确保了数据更新的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When two people attempt to update the same record near the same time, one of the updates will likely be overwritten. You can solve this problem with optimistic locking.
# migrations/011_add_products_lock_version.rb
add_column :products, :lock_version, :integer, :default => 0, :null => false

# products_controller.rb
def update
@product = Product.find(params[:id])
if @product.update_attributes(params[:product])
flash[:notice] = "Successfully updated product."
redirect_to product_path(@product)
else
render :action => 'edit'
end
rescue ActiveRecord::StaleObjectError
@product.reload
render :action => 'conflict'
end
<!-- _form.rhtml -->
<%= f.hidden_field :lock_version %>

<!-- conflict.rhtml -->
<% title "Edit Product Conflict" %>

Someone edited the product the same time you did. Please re-apply your changes to the product.

<h2>Your Submission:</h2>
<pre>
<% params[:product].each do |name, value| %>
<%=h name.humanize %>: <%=h value %>
<% end %>
</pre>

<h2>Edit Product:</h2>
<% form_for :product, :url => product_path(@product), :html => { :method => :put } do |f| %>
<%= render :partial => 'form', :locals => { :f => f } %>
<%= submit_tag 'Resolve' %>
<% end %>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值