Unable to get "has_many :after_add" to work - need help

Can someone tell me what I’m doing wrong? I’ve spent way too much
time on this


class Picture < ActiveRecord::Base
has_many :ratings, :after_add => :increment_rating, :after_remove
=> :decrement_rating

def increment_members(rating)
self.rating += rating.amount
save!
end
end


class Rating < ActiveRecord::Base
belongs_to :picture
end


class CreatePictures < ActiveRecord::Migration
def self.up
create_table :pictures do |t|
t.column :title, :string
t.column :rating, :float
end
end

def self.down
drop_table :pictures
end
end


class CreateRatings < ActiveRecord::Migration
def self.up
create_table :ratings do |t|
t.column :picture_id, :integer
t.column :amount, :float
end
end

def self.down
drop_table :ratings
end
end


script/console
p = Picture.create(:title => ‘p02’)
Rating.create(:amount => 5, :picture => p)


Try p.ratings.create(:amount => 5). Otherwise you’re not going to
trigger the callback since the callback is defined in the Picture model.

A more reliable callback would be an after_create in the Rating model,
like so:

class Rating < ActiveRecord::Base
belongs_to :picture

def after_create
self.picture.update_attribute(:rating, self.picture.rating +
self.amount)
end

def after_destroy
self.picture.update_attribute(:rating, self.picture.rating -
self.amount)
end
end

This would trigger either through p.ratings.create(:amount => 5) or
Rating.create(:amount => 5, :picture => p)

-matthew

p.ratings.create(:amount => 5) didn’t work either… any other
thoughts on how to make this work?

I did think about using after_create in the Rating model (and will end
up doing that if I can’t get this to work) but it makes more sense in
my head to have an :after_add in the Picture model. Does :after_add
just not work or am I missing something?

I think you were almost there the first try.

script/console
p = Picture.create(:title => ‘p02’)
r = Rating.create(:amount => 5)
p.ratings << r

The after_add is only fired when using the << function to add the
object to the collection.

–nkryptic