Friday, August 16, 2013

Rails Callbacks: Being a Good Neighbor

Using callbacks like before_save, after_destroy, etc. in your rails models is a very important way to ensure that the things you assume about your data are actually enforced.

If you return false, and halt the callback chain, be sure to include error messages via errors.add("..."), so the caller knows why it failed.

Class User < ActiveRecord::Base

  before_save :update_other_subsystem

  def update_other_subsystem
    success = some_other_subsystem.send("new user!")
    unless success
     errors.add("couldn't update the subsystem")
     return false

This is a pretty contrived example, but you get the idea.

No comments:

Post a Comment