Rails7嵌套模型创建报错:ActiveModel::NestedError求助
解决Rails 7嵌套模型保存时的必填关联错误
问题原因
Rails 5及后续版本中,belongs_to关联默认强制要求关联对象存在(外键不可为空)。在嵌套创建Survey及其子对象时,父对象(Survey、SurveyQuestion)尚未保存到数据库,还未生成主键ID,导致子对象的外键字段为空,触发了blank验证错误。
解决方案
在子模型的belongs_to关联中添加optional: true选项,允许子对象在父对象未完成保存时暂时不关联,待父对象保存后Rails会自动填充外键:
修改SurveyQuestion模型
class SurveyQuestion < ApplicationRecord belongs_to :survey, foreign_key: 'IdSurvey', inverse_of: :survey_questions, optional: true has_many :survey_question_options, foreign_key: 'IdSurveyQuestion', dependent: :destroy accepts_nested_attributes_for :survey_question_options self.table_name = 'SurveyQuestion' self.primary_key = 'IdSurveyQuestion' end
修改SurveyQuestionOption模型
class SurveyQuestionOption < ApplicationRecord belongs_to :survey_question, foreign_key: 'IdSurveyQuestion', inverse_of: :survey_question_options, optional: true self.table_name = 'SurveyQuestionOption' self.primary_key = 'IdSurveyQuestionOption' end
验证修改
修改后重新执行创建操作:
s = Survey.new(Title: 'S', survey_questions_attributes: [{Title: 'Q', survey_question_options_attributes: [{Title: 'O'}]}]) s.save
此时嵌套对象会按顺序保存:先保存Survey生成IdSurvey并赋值给SurveyQuestion的IdSurvey,再保存SurveyQuestion生成IdSurveyQuestion并赋值给SurveyQuestionOption的IdSurveyQuestion,最终所有对象都会成功保存到数据库。
内容的提问来源于stack exchange,提问作者Behnam
相关产品推荐
相关产品推荐

