0

我试图一次保存两个模型(一对多)。我的代码如下所示:

@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
4

1 回答 1

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
于 2013-09-13T10:03:31.450 回答