1

My app has points / awards that can be achieved after a number of actions take place, which generally trigger when a record has been added (completing a mission, etc.)

I wrote a fairly involved function that audits all of the data, and awards the proper amount of points, user ranking, etc. This needs to be called after each one of these records is saved.

I know I can use Observers to call the function after a number of model saves, but I am unclear on where exactly the put said function, and how to call it.

Much appreciated in advance!

John R
  • 301
  • 3
  • 14

1 Answers1

1

Observers usually go in app/models/. You can automatically generate an observer class for a model with the command rails generate observer YourModel. This will generate the file `app/models/your_model_observer.rb'.

By the way, aftersave is not a very descriptive method name. If it does a lot of things it's better to break it up into several methods each of which do one thing, and give each a descriptive name, e.g.:

class YourModelObserver < ActiveRecord::Observer
  def after_save your_model_instance
    calculate_points your_model_instance
    assign_awards    your_model_instance
  end

  private
  def calculate_points inst
    # ...
  end

  def assign_awards inst
    # ...
  end
end
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • [The documentation](http://api.rubyonrails.org/classes/ActiveRecord/Observer.html) describes how to create an observer that observes several models, or you could write a separate class or module ([usually](http://stackoverflow.com/questions/285148/where-should-my-non-model-non-controller-code-live#285152) in `lib/`) and include it in your models or observers. – Jordan Running Jan 07 '12 at 01:34