以下模型给出:
class Question < ActiveRecord::Base has_many :answers end class Answers < ActiveRecord::Base belongs_to: question validates :comment, presence: true end打电话时
question = Question.new question.answers.build question.valid?valid? 返回false因为相关答案无效。 写作时
has_many :answers, validate: falseQuestion valid? 返回true 。
这是一个错误还是在使用has_many时需要自动验证相关模型? Rails指南明确解释了validate_associated与has_many关系的使用: http : //guides.rubyonrails.org/active_record_validations_callbacks.html#validates_associated
Following models are given:
class Question < ActiveRecord::Base has_many :answers end class Answers < ActiveRecord::Base belongs_to: question validates :comment, presence: true endWhen 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: falsein 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
最满意答案
这绝对不是一个bug。
你已经创建了一个Question 您已经告诉Rails附加一个新的Answer实例并将其与这个新Question联系起来 然后你问“Rails,我创建的Question/Answer模型和关联是否已准备好保存到数据库中?”正如您所发现的,Rails会在您的案例中说“不” 。
我从未使用过,也不关心validates_associated 。 但是,我可以向您指出文档,解释您为什么会看到自己的行为。
Active Record Autosave Association虽然上面的源文件中的文档值得一读,但我会为你提取这些内容
你没有在你的:answers关联中指定:autosave => SOMETHING 因此,Rails默认情况下会尝试在新Question上保存新构建/关联的Answer 保存将失败,因为Answer无效请注意:autosave => false与不声明不同:autosave。 如果:自动保存选项不存在,则会保存新关联。
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 AssociationThough the documentation at the above source file is worth reading in it's entirety, I'll pull out this bit for you
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 invalidNote that :autosave => false is not same as not declaring :autosave. When the :autosave option is not present new associations are saved.
更多推荐
发布评论