I *think* that when you specify the *_id in your validations, that AR will
not figure things out for you, and will be more literal:

class Child < ActiveRecord::Base

  belongs_to :parent

  validates_presence_of :parent_id
end


If you change the validation to:

validates_presence_of *:parent*

*Then, *Rails knows to introspect and figure the proper order in which the
SQL must be executed (parent is an association, not column name).  In the
end, it wraps the SQL in a transaction and will create both new objects (in
the proper order).  If you specify a column name (like parent_id), then
Rails is not validating the association, but validating the column.  Then it
is up to the programmer to create the objects in the proper order.

Cheers

Ben

On Fri, Jul 22, 2011 at 4:54 PM, Greg Willits <[email protected]> wrote:

> On Jul 22, 2011, at 4:16 PM, Glenn Little wrote:
>
> > How does one enforce that any child record saved has a parent?  I've got
> this:
>
> Review the ActiveRecord callbacks. Look at the order.
>
> You need to tell the child what its parent is. You can trigger when this
> happens using the callbacks.
>
> Write a before_validation method which ensures the parent_id has a value
> (which is likely going to be something you pass to the child in the .new /
> .initialize method).
>
> At least, that's how I do it, but maybe there's supposed to be a better
> way.
>
> -- gw
>
>
> --
> SD Ruby mailing list
> [email protected]
> http://groups.google.com/group/sdruby
>

-- 
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby

Reply via email to