views:

46

answers:

2

I'm setting up an after_save callback in my model observer to send a notification only if the model's published attribute was changed from false to true. Since methods such as changed? are only useful before the model is saved, the way I'm currently (and unsuccessfully) trying to do so is as follows:

def before_save(blog)
  @og_published = blog.published?
end

def after_save(blog)
  if @og_published == false and blog.published? == true
    Notification.send(...)
  end
end

Does anyone have any suggestions as to the best way to handle this, preferably using model observer callbacks (so as not to pollute my controller code)?

+1  A: 

You just add an accessor who define what you change

class Post < AR::Base
  attr_reader :what_changed

  before_filter :what_changed?

  def what_changed?
    @what_changed = changes || []
  end

  after_filter :action_on_changes

  def action_on_changes
    @what_changed.each do |change|
      p change
    end
  end
end
shingara
+3  A: 

In your after_update filter on the model you can use _changed? accessor (at least in Rails 3, not sure for Rails 2). So for example:

class SomeModel < ActiveRecord::Base
  after_update :send_notification_after_change

  def send_notification_after_change
    Notification.send(...) if (self.published_changed? && self.published == true)
  end

end

It just works.

pawien
Have tied it in Rails 2.0.5 - works perfectly
stephenr
Forget what I said above - it DOESN'T work in Rails 2.0.5. So a useful addition to Rails 3.
stephenr
Right on, works great - Rails 2.3.8 included.
modulaaron
Do I need to use `self.published_changed?`, or can I use just `published_changed?`?
Tobias Cohen
should work without self but I'm using it to explicitly show that I'm working with attributes/methods of self
pawien