【发布时间】:2021-03-11 17:55:20
【问题描述】:
是否允许在 ActiveRecord 的回调中锁定关联对象?
class Product < ApplicationRecord
# stock (integer)
has_many :sales
end
class Sale < ApplicationRecord
# quantity (integer)
belongs_to :product
before_save do
self.product.lock!
throw :abort if self.product.stock < self.quantity
end
end
这个想法是防止创建库存不足的销售记录。
【问题讨论】:
标签: ruby-on-rails ruby activerecord