给出了以下模型:
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: false
在
Question
valid?
返回 true
.使用
has_many
时是错误还是需要相关模型是否自动验证? Rails 指南明确解释了 validate_associated
的使用与 has_many
关系:http://guides.rubyonrails.org/active_record_validations_callbacks.html#validates_associated
最佳答案
绝对是不是 一个错误。
Question
Answer
实例。并将其与这个新 Question
联系起来Question/Answer
模型和关联是否准备好保存到数据库中?” 正如您所发现的,Rails 会说 “不”在你的情况下。
我没用过也不在意
validates_associated
.但是,我可以向您指出文档,解释为什么您会看到自己的行为。尽管上述源文件中的文档值得一读,但我会为您提取这一部分
Note that :autosave => false is not same as not declaring :autosave. When the :autosave option is not present new associations are saved.
:autosave => SOMETHING
在您的 :answers
协会Answer
在您的新 Question
Answer
无效 关于ruby-on-rails - 为什么 ActiveRecord 会自动验证 has_many 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15680111/