Am I right in that it seems the only way to get the :before_add to
prevent the addition is the actually throw an exception in my :before_add
callback routine? Which means I now have to deal with catching/handling
an exception in non-critical code (this is not where my saves and
transactions are).
Also, it seems to be stuffing an argument into my callback routine call.
Is this documented anywhere other than on the
ActiveRecord::Associations::ClassMethods
api doc page? That's a little sparse regarding this topic.
In the meantime, Kerry's workaround works. Feels a little odd, will
probably look a little ugly a month from now, but it does work. :-)
Thanks!
-glenn
Martin Emde wrote:
> collection.build is the only way that currently exists in active record.
> You could look into before_add callbacks. They get called with the new
> record and you could perform your conditional there.
> Martin Emde
> Tw: @martinemde
>
>
> On Fri, Jul 10, 2009 at 6:15 PM, Kerry Foley <[email protected]
> <mailto:[email protected]>> wrote:
>
>
> Not sure that this is the best way but how about mixing the two?
>
> c = Child.new(params)
> p.children.build(params) unless (some conditional stuff on c)
>
> Regards,
> Kerry
>
> Glenn Little wrote:
> > I'm looking for a way to add new child objects to a parent's has_many
> > collection, but without doing an immediate save.
> >
> > There is build():
> >
> > p = Parent.new(stuff)
> > p.children.build(params)
> >
> > But the problem is I'd like to do this conditionally without
> having to
> > pick apart params. I'd do:
> >
> > c = Child.new(params)
> > p.children << c unless (some conditional stuff on c)
> >
> > or
> >
> > p.children.push(c) unless (some conditional stuff on c)
> >
> > but both of those immediately save the child object c.
> >
> > Lastly, associating the child to the parent via the child:
> >
> > p = Parent.new(stuff)
> > c = Child.new(params)
> > c.parent = p unless (some conditional stuff on c)
> >
> > leaves the parent unaware of the child in its p.children collection.
> >
> > Is there a clean rails-y idiom I'm missing?
> >
> > Thanks much...
> >
> > -glenn
> >
> > >
> >
> >
>
>
>
>
> >
--~--~---------~--~----~------------~-------~--~----~
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby
-~----------~----~----~----~------~----~------~--~---