Thanks Fred and Robert and anyone else who has read this!

I've had some more time to look at this and it appears there is no way
in rails to modify a parent model's attributes from a child model
during a transaction. I wrote a basic app to test it out.

Assume Parent has_many Children and Child belongs_to Parent. Also,
Parent has a before_save filter (we'll look at what it does in a
moment). Child also has a before_filter that updates an attribute in
it's Parent.

Version 1: In one example, the Parent's before_save filter *builds*
three Children. Because it is a "build" and not a new or create, the
child objects are saved when the parent is saved. In this case, the
child's change to its parent attribute just disappears, although the
Child is successfully instantiated. http://pastie.org/1106223

Version 2: Okay, then I tried the same thing, this time using create
instead of build in the Parent's before_save filter. That generates an
error, "You cannot call create unless the parent is saved." Which
makes sense.

Version 3: Same as Version 1, but make the Parent's filter after_save.
In this case, the before_filter of the children is never called (and
same result if the Child's filter is changed to an after_save, it just
isn't called).

Version 4: Same as Version 1, but remove the callback in the child and
just call that method directly from the parent immediately after the
build. You get a "undefined method" from the Child's method because
the parent is nil at this point.

Version 5: Like Version 4, but uses after_save instead of before_save.
The results are just like Version 1, the Child's method is called,
changes to the Parent aren't saved, but the children are saved.

In these examples, I used
  Parent.create
and
  p=Parent.new
  p.save
and get the same results each time. The results are also in the pastie
(http://pastie.org/1106223).

So, if there are limitations on what you can do in a callback filter,
we should  probably documented it somewhere. However, I might even
call it a bug. What do you think?

d.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to