我有一个非常简单的rails模型,我试图在更新之前更改值:
before_update { self.notes = "from the model" }
但此更新无效,有什么问题?
由于
答案 0 :(得分:0)
尝试
before_update 'self.notes = "from the model"'
或者
before_update { |record| record.notes = "from the model" }
或者
before_update :change_notes
private
def change_notes
self.notes = "from the model"
end
确保您在self.notes
回调后没有更新before_update
,否则您将看不到更改。
答案 1 :(得分:0)
请试一试。
before_save :change_notes
private
def change_notes
self.notes = "from the model"
end
答案 2 :(得分:0)
另一种方法是使用proc。我通常倾向于使用这种模式:
set_callback :update, :before do |model|
model.notes = "from the model"
end
这样做可以让您明确指定要更改的模型实例(即在这种情况下" model")。回调将在运行时自动将模型实例传递给Proc。
然而,只是一个简单的说明 - 如果你有一个名为"模型"的模型类,有一个名为" my_model"的实例,请确保你尝试的是什么modify(即" notes")实际上是实例的一部分,而不是类。如果它是类的一部分,它最多会出错,立即告诉你某些事情是错误的,或者最坏的情况是设置一个所有实例将共享的类变量导致非确定性结果。