我一直在通过在模型中使用它来阻止对某些模型的更新:
def update
self.errors.add_to_base( "Cannot update a #{ self.to_s }" )
end
我现在正在编写一个插件,为模型提供一些额外的功能,我需要更新模型中的一个字段。如果我不使用插件,我会直接在模型中执行此操作...
def update
if self.changed == ['my_field']
super
else
self.errors.add_to_base( "Cannot update a #{ self.to_s }" )
end
end
我无法从我的插件中执行相同的操作,因为我不知道更新行为是 ActiveRecord 的默认行为,还是已被覆盖以防止更新。有没有另一种方法可以防止记录更新,同时允许我覆盖特定字段(并且仅在我的插件应用于此模型的情况下)。
最佳答案
首先,您应该为这类事情使用 before_update 回调,而不是覆盖更新。其次,您可以将可更新的属性存储在模型上,然后使用插件更新它们。我只是在浏览器中写的,所以它可能是错误的。
attr_accessor :updatable_attributes
before_update :prevent_update
private
def prevent_update
return true if self.changed == self.updatable_attributes
self.errors.add_to_base "Cannot update a #{ self.to_s }"
false
end
end
关于ruby-on-rails - 除了在一个字段上,我如何禁止更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4191912/