ruby-on-rails - 防止记录在特定条件后被编辑
问题描述
我有一个 Rails 应用程序,其中有一条名为 Listing 的记录,has_many
与 Offer 相关。现在一个Listing可以有很多Offer,但是当Listing有一个Offer的:status被接受时,我希望这个Listing不能再被编辑。
我该怎么办?我正在考虑使用像 check_offer_status 这样的回调方法,然后在列表编辑操作上使用 before_action?这是要走的路还是我应该考虑别的?
解决方案
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 的情况。
推荐阅读
- async-await - 我可以跳过 HttpWebRequest 的 GetResponseAsync() 上的“等待”吗
- javascript - 如何提高 React 中递归组件的性能?
- tensorflow - 堆叠 LSTM 的初始状态结构
- r - 根据 2 个条件 ggplot2 格式化线型
- visual-studio - 如何调试 Microsoft Store 包?
- node.js - 为什么使用`yarn link`?为什么不只是 node_modules 中的符号链接?
- r - 如何防止在缺失数据行数超过 X 的值之间进行插值?
- c++ - 如何使用重载运算符修复此内存泄漏?
- maven - GlassFish/Payara - 定义的 maven 依赖抛出 ClassNotFoundException
- python - 如何根据特定的字符串值从 Excel 电子表格中提取工作表的内容