Why ActiveRecord automatically validates has_many association

activerecord, ruby-on-rails, ruby-on-rails-3, validation

Solution

It's most definitely not a bug.

- You've created a `Question`

- You've told Rails to attach a new instance of `Answer` and relate it to this new `Question`

- You're then asking "Rails, is this `Question/Answer` model and association I've created ready to be saved to the database?"

As you've found, Rails will say "No" in your case.

I have never used and do not care about `validates_associated`. I can however point you to documentation explaining why you're seeing the behavior you are.

- Active Record Autosave Association

Though the documentation at the above source file is worth reading in it's entirety, I'll pull out this bit for you

Note that :autosave => false is not same as not declaring :autosave. When the :autosave option is not present new associations are saved.

- You have not specified `:autosave => SOMETHING` on your `:answers` association

- Because of this, Rails by default is going to try and save your newly build/associated `Answer` on your new `Question`

- The save will fail because the `Answer` is invalid

Problem

Following models are given: ``` class Question < ActiveRecord::Base has_many :answers end class Answers < ActiveRecord::Base belongs_to: question validates :comment, presence: true end ``` When calling ``` question = Question.new question.answers.build question.valid? ``` `valid?` returns `false` because the associated answer is not valid. When writing ``` has_many :answers, validate: false ``` in `Question` `valid?`returns `true`. Is it a bug or is it desired when using `has_many` the associated models are validated automatically? The Rails Guides explicitly explain the use of `validate_associated` with a `has_many` relationship: http://guides.rubyonrails.org/active_record_validations_callbacks.html#validates_associated

Original source