Rails after_commit 回调中更新 Property 平均评分导致 SQLite 锁定
1. 修正基础关联错误
现有代码存在关联缺失、参数错误问题:
- 若外键设计为
bookings.review_id(即当前Booking belongs_to :review的写法),Review必须先声明直接关联has_one :booking,才能通过through关联获取Property Property必须先声明has_many :bookings,且through参数需用复数:bookings,原代码单数写法会直接抛出关联不存在错误
常规业务逻辑下(一个预订对应一条评论,评论依附预订存在),更合理的外键设计是把booking_id放在reviews表,对应Review belongs_to :booking、Booking has_one :review,关联逻辑更顺畅。
2. 修正持久化调用错误
原代码中property.average_rating.save!属于错误调用:average_rating是数值型字段,没有save!方法。赋值后需要调用Property实例的保存方法,或直接用字段级更新接口跳过冗余流程。
另外round(2).to_i会直接截断小数,例如3.99会被转成3,若需要四舍五入取整直接调用round即可。
3. 选择正确的回调类型
锁冲突根因
SQLite默认采用DELETE日志模式,写操作会锁定整个数据库文件。after_commit会在当前事务提交后新开独立事务执行更新,如果存在外层未提交事务、其他数据库连接持有写锁,或读操作的共享锁未释放,就会触发SQLite3::BusyException。
回调选型结论
同库的派生统计字段更新,优先使用after_save,不要使用after_commit:
after_save在记录SQL执行完成、事务提交前触发,更新Property的操作会加入当前事务,仅需获取一次写锁,不会产生锁竞争- 数据一致性天然有保障:如果事务回滚,Review和平均分更新会一同回滚,不会产生脏数据
after_commit仅适合不需要跟随当前事务回滚的操作,比如发送通知、投递异步任务,不适合同库关联字段更新
4. 优化数据库操作减少锁占用
不要加载全部评论后用Ruby聚合,直接调用数据库AVG函数计算;如果不需要触发Property的校验、回调,使用update_column直接更新字段,减少不必要的SQL执行,缩短锁持有时间。
如果评论删除也需要刷新平均分,补充after_destroy回调。
5. 必用after_commit的兼容方案
如果必须使用after_commit,修改SQLite配置开启WAL模式,支持读写并发,同时配置锁等待超时,避免直接报错。在config/database.yml中添加配置:
default: &default adapter: sqlite3 pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> timeout: 5000 variables: journal_mode: WAL
下面给出两种外键设计的完整代码,均采用after_save回调,无锁冲突风险。
方案一:保留现有外键设计(外键在bookings表)
# Review 模型 class Review < ApplicationRecord has_one :booking has_one :property, through: :booking after_save :refresh_property_average_rating after_destroy :refresh_property_average_rating private def refresh_property_average_rating return unless booking avg = booking.property.reviews.average(:rating).to_f.round(2) booking.property.update_column(:average_rating, avg) end end
# Property 模型 class Property < ApplicationRecord has_many :bookings has_many :reviews, through: :bookings end
# Booking 模型 class Booking < ApplicationRecord belongs_to :property belongs_to :review end
方案二:常规业务设计(外键在reviews表,推荐)
# Review 模型 class Review < ApplicationRecord belongs_to :booking has_one :property, through: :booking after_save :refresh_property_average_rating after_destroy :refresh_property_average_rating private def refresh_property_average_rating avg = property.reviews.average(:rating).to_f.round(2) property.update_column(:average_rating, avg) end end
# Property 模型 class Property < ApplicationRecord has_many :bookings has_many :reviews, through: :bookings end
# Booking 模型 class Booking < ApplicationRecord belongs_to :property has_one :review end
高性能单SQL版本
如果数据量较大,可以直接用单条UPDATE语句完成统计和更新,无需加载模型实例,进一步减少数据库交互:
# 以推荐的外键设计为例 class Review < ApplicationRecord belongs_to :booking has_one :property, through: :booking after_save :refresh_property_average_rating after_destroy :refresh_property_average_rating private def refresh_property_average_rating Property.where(id: booking.property_id).update_all( <<~SQL.squish average_rating = ( SELECT ROUND(AVG(reviews.rating), 2) FROM reviews INNER JOIN bookings ON bookings.id = reviews.booking_id WHERE bookings.property_id = properties.id ) SQL ) end end
内容的提问来源于stack exchange,提问作者hillybob991

