我有一个带有 amount
的模型我正在跟踪查看此金额是否随 Model.amount_changed?
发生变化与 before_save
这工作正常,但是当我查看 amount_was
时和 amount_change?
它只返回更新的金额而不是以前的金额。而这一切都发生在它被保存之前。它知道何时更改属性,但不会返回旧值。
想法?
class Reservation < ActiveRecord::Base
before_save :status_amount, :if => :status_amount_changed
def status_amount_changed
if self.amount_changed? && !self.new_record?
true
else
false
end
end
def status_amount
title = "Changed Amount"
description = "to #{self.amount_was} changed to #{self.amount} units"
create_reservation_event(title, description)
end
def create_reservation_event(title, description)
Event.create(:reservation => self, :sharedorder => self.sharedorder, :title => title, :description => description, :retailer => self.retailer )
end
end
最佳答案
如果您想跟踪模型中的更改,Rails 提供 "Dirty Objects" .
例如。您的型号有 name
属性:
my_model = MyModel.find(:first)
my_model.changed? # it returns false
# You can Track changes to attributes with my_model.name_changed? accessor
my_model.name # returns "Name"
my_model.name = "New Name"
my_model.name_changed? # returns true
# Access previous value with name_was accessor
my_model.name_was # "Name"
# You can also see both the previous and the current values, using name_change
my_model.name_change #=> ["Name", "New Name"]
如果要将旧值存储在数据库中,可以使用:
amount
amount_was
检索 的值金额在改变之前。 您可以在
update_attributes
期间保存两者称呼。否则,如果您不需要
amount_was
历史,你可以只使用两个实例变量。如果你需要更多的东西,比如跟踪你的模型历史,Rails 有一个很好的专用插件。
至于其他不错的话题瑞恩贝茨谈论我here: Railscasts #177
关于ruby-on-rails - rails : attribute_changed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2942162/