Rails:attribute_changed?

the*_*gah 8 ruby-on-rails

我有一个具有一个模型amount,我查看是否有这个量发生变化的一个Model.amount_changed?具有before_save工作正常,但是当我检查,看看amount_wasamount_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
Run Code Online (Sandbox Code Playgroud)

mic*_*ino 29

如果要跟踪模型中的更改,Rails会提供"脏对象".例如,您的模型有一个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"]
Run Code Online (Sandbox Code Playgroud)

如果要将旧值存储在数据库中,可以使用:

  1. 模型属性 amount
  2. 换句话说,方法_就在上面的属性上:在更改之前amount_was检索金额的值.

您可以在update_attributes通话期间保存两者.否则,如果您不需要amount_was历史记录,则可以使用两个实例变量.

如果你需要更多的东西,比如跟踪你的模型历史,Rails有一个很好的专用插件.至于其他好话题,瑞安贝茨在这里谈到我:Railscasts#177