- 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?
Active Record Association Collection
AssociationCollection is an abstract class that provides common stuff to ease the implementation of association proxies that represent collections. See the class hierarchy in AssociationProxy.
You need to be careful with assumptions regarding the target: The proxy does not fetch records from the database until it needs them, but new ones created with build are added to the target. So, the target may be non-empty and still lack children waiting to be read from the database. If you look directly to the database you cannot assume that’s the entire collection because new records may have been added to the target, etc.
If you need to work on all current children, new and existing records, load_target and the loaded flag are your friends.
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 => []