When to use "validates_associated" v "validate => true"

Viewed 10495

It seems that in rails you can define association validations in two places, either on the association itself:

class Child

  belongs_to :parent, :validate => true

end

Or as a validation callback:

class Child

  belongs_to :parent

  validates_associated :parent

end

What is the difference between these two methods?

Testing the difference

I thought that maybe the former creates a backpressure and enforces that the parent is only valid if the child is valid:

i.e. (when setting :validate => true)

child.valid? # => false
child.parent.valid? # => also evaluates to false because of the :validate => true condition


# do whatever it takes to make the child valid again
#...
child.valid? # => true
child.parent.valid? # => true

However I tested it and this doesn't happen. So what's the difference (if any) between the two methods?

1 Answers
Related