我试图一次保存两个模型(一个到多个)。我的代码如下所示:
@submission = Submission.new(submission_params)
@submission_asset = @submission.attachments.new(submission_asset_params)
@submission_asset.attachment_type = 'submission_asset'
if @submission.save
# render or redirect here
else
@submission.errors
end
但是当我运行此操作时,我收到此错误@messages={:attachments=>["is invalid"]}
。我认为这是因为我的附件模型有这个:
# Attachment model snippet
validates :attachable_id, :attachable_type, presence: true
但是要确保它附加到Submission
。但是,当我删除或注释掉验证时,它可以工作并保存两个模型和关联。
如何进行此保存?
修改
class Submission < ActiveRecord::Base
has_many :attachments, as: :attachable, dependent: :destroy
end
class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
validates :attachable_id, :attachable_type, presence: true
end
答案 0 :(得分:0)
@submission_asset = @submission.attachments.build(submission_asset_params)
更新:
class Submission < ActiveRecord::Base
has_many :attachments, as: :attachable, inverse_of: :attachable, dependent: :destroy
end
class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
validates :attachable, presence: true
end