首页 > 解决方案 > 防止记录在特定条件后被编辑

问题描述

我有一个 Rails 应用程序,其中有一条名为 Listing 的记录,has_many与 Offer 相关。现在一个Listing可以有很多Offer,但是当Listing有一个Offer的:status被接受时,我希望这个Listing不能再被编辑。

我该怎么办?我正在考虑使用像 check_offer_status 这样的回调方法,然后在列表编辑操作上使用 before_action?这是要走的路还是我应该考虑别的?

标签: ruby-on-railsruby

解决方案


Rails 方法是实现该readonly?方法

class Listing < ApplicationRecord
  has_many :offers
  def readonly?
    offers.where(accepted: true).exists?
  end
end

每当您保存记录时都会调用此方法,并且会引发ActiveRecord::ReadOnlyRecord错误。如果您想防止错误并提供更好的用户反馈,您可以添加验证:

class Listing < ApplicationRecord
  has_many :offers
  validates :is_editable, on: :update

  def readonly?
    offers.where(accepted: true).exists?
  end
  
  def is_editable
    errors.add(:base, 'Listing cannot be edited') if readonly?
  end
end

然而,这只是一个薄弱的保证,并且仍然容易出现潜在的竞争条件以及任何将绕过 Konstantin Strukov 所描述的 AR 的情况。


推荐阅读