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
validates is used for normal validations presence , length , and the like. validate is used for custom validation methods validate_name_starts_with_a , or whatever crazy method you come up with. These methods are clearly useful and help keep data clean. That test fails.
Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.
Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship. Whether it; belongs_to, has_many, has_one, has_one:through, has_and_belongs_to_many.
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
It's most definitely not a bug.
Question
Answer
and relate it to this new Question
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.
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.
:autosave => SOMETHING
on your :answers
associationAnswer
on your new Question
Answer
is invalidIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With