You can add:

validates_presence_of :parent

on your child model to enforce that no need to use parent_id

Also unsaved objects don't have an id therefore what you're trying fails
make sure to save the parent first, or look for
accepts_nested_attributes_for in the rails api.

Hope this helps.

On Fri, Jul 22, 2011 at 4:16 PM, Glenn Little <[email protected]> wrote:

> How does one enforce that any child record saved has a parent?  I've got
> this:
>
> Parent: has_one :child
> Child:   belongs_to :parent
>
> So, Child records have a parent_id.
>
> If, in the Child model, I put:
>
>  validates :parent_id, :presence => true
>
> I get a failure when I do this:
>
> c = Child.new
> p = Parent.new
> c.parent = p
> c.save!
>
> It fails the validation with "parent_id can't be blank".  As if it's
> trying to save the child first, before the associated parent?
>
> If I take away the presence validation, it works fine.
>
> Or, if I leave the validation there, but save the two sides by hand:
>
> c = Child.new
> p = Parent.new
> p.save!
> c.parent = p
> c.save!
>
> It also seems to work.
>
> Is it just not smart enough to know it needs to save the parent first
> so it can get the id?  Or am I just not smart enough to use what rails
> provides? :)
>
> Thanks for any thoughts...
>
> -glenn
>
> --
> SD Ruby mailing list
> [email protected]
> http://groups.google.com/group/sdruby




-- 
Enrique Vidal

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

Reply via email to