Flowdock

Notes posted by giams

RSS feed
August 13, 2008 - (v1.2.6 - v2.1.0)
3 thanks

Insertion/Deletion callbacks

All ActiveRecord associations except for has_many :through support callbacks for pre- and post-insertion/deletion via the following, self-documenting parameters:

Adding to an Association

:before_add

:after_add

Removing from an Association

:before_remove

:after_remove

The flexibility that these callbacks offer is quite handy, but I’ll demonstrate with a silly example: logging each insertion and deletion.

class Ship < ActiveRecord::Base

  has_many :pirates, 
    :after_add => :say_hello,
    :before_remove => :say_goodbye

  private

  def say_hello(pirate)
    STDOUT.write("hello #{pirate.name} ")
  end

  def say_goodbye(pirate)
    STDOUT.write("goodbye #{pirate.name} ")
  end

end

Now, we’ll see confirmation when we add/remove Pirates in the console from our ship (and yes, this must be the ghetto):

>> jolly_roger = PirateShip.new

=> #<Ship id: nil, created_at: nil, updated_at: nil>
>> jolly_roger.pirates << Pirate.create(:name => 'Black Bart')
hello Black Bart => [#<Pirate id: 1, name: "Black Bart", created_at: "2008-07-29 14:41:13", updated_at: "2008-08-11 11:51:25">
>> jolly_roger.pirates.first.delete
goodbye Black Bart => []