Robbo February 2016

rails validates_associated if/unless not working

I have a parent with a has_many association to children. The child class has some of its own validations. I only want the child validations to run if a value on the parent is set to true. For some reason, no matter what i try the validations on the child are always run.

parent class

class Parent < ActiveRecord::Base

  has_many :children
  accepts_nested_attributes_for :children, allow_destroy: true, reject_if: :all_blank
  validates_associated :children, if: Proc.new { |m| m.do_validation == true }

end

child class

class Child < ActiveRecord::Base
  validates_presence_of :name
end

Am i using validates_associated incorrectly here?

Thanks

Answers


Nermin February 2016

validates_associated is to perform validations on associated records, but in the context of the caller. In your example when you create Parent if all validations on Parent pass, then it will call validations on the Child ( all related children), and if some of those validations fail, the create of the Parent will fail.

This also means when you create Child it will call all validations on the Child, it does not mater that you have put if in the Parent class, because validations are related to the Child model.

To prevent validations of Child to be executed every time when record is created, updated, ... you have to add if clause in the Child model.

Post Status

Asked in February 2016
Viewed 3,795 times
Voted 11
Answered 1 times

Search




Leave an answer