代码之家  ›  专栏  ›  技术社区  ›  index

Rails4:在has_many模型验证器上使用has_many保存对象失败

  •  0
  • index  · 技术社区  · 12 年前

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

    @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
    
    1 回复  |  直到 12 年前
        1
  •  0
  •   Oleg Haidul    12 年前
    @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