v1.2.6 -
Show latest stable
-
1 note
- Superclass:
ActiveRecord::Associations::AssociationProxy
- 1.0.0 (0)
- 1.1.6 (0)
- 1.2.6 (0)
- 2.0.3 (0)
- 2.1.0 (0)
- 2.2.1 (37)
- 2.3.8 (0)
- 3.0.0 (2)
- 3.0.9 (-1)
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
Register or
log in
to add new notes.
giams -
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 => []