Rails4:在has_many模型验证器上使用has_many保存对象失败(Rails4: Save object with has_many fails on the has_many model validator)
我试图一次保存两个模型(一个到多个)。 我的代码如下所示:
@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
I'm trying to save two models (one to many) in one time. My code looks like this:
@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
But when I run this I get this error
@messages={:attachments=>["is invalid"]}
. I think it's because my attachment model has this:# Attachment model snippet validates :attachable_id, :attachable_type, presence: true
But it's to ensure it is attached to a
Submission
. But when I remove or comment out the validation it works and saves the two models and the association.How do I make this save?
EDIT
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
原文:https://stackoverflow.com/questions/18783394