Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validate child before save

I have an usual nested model

class Parent
  has_one :child
  accepts_nested_attributes_for :child
end

class Child
  belongs_to :parent

  validate :name, :presence => true
end

If I try to save a child without a name, it is prohibited, but if I save the parent with the child nested, if ignores the validation.

I don't want to repeat my child validations with :reject_if.

How can I validate the child and, only if the child is valid, save the parent along with the child?

like image 616
Pedro Bernardes Avatar asked Jul 29 '14 14:07

Pedro Bernardes


1 Answers

You should use validates_associated:

class Parent
  has_one :child
  accepts_nested_attributes_for :child
  validates_associated :child
end
like image 131
Marek Lipka Avatar answered Nov 01 '22 11:11

Marek Lipka