Rails Paperclip附件未保存,因为未分配多态id

时间:2014-04-10 19:51:44

标签: ruby-on-rails paperclip

我是全新的。我一直在使用rails应用程序几个小时,需要一个答案。我搜索并尝试了许多与我想要完成的事情相关的建议,但无济于事。我昨天为我的rails应用程序运行了paperclip gem,并且轻松地为单个模型添加附件。但是,我定义了一个不可知的多态附件表来保存所有需要此功能的模型的附加文件。

我的问题是我无法通过嵌套参数获取附加文件。我的所有参数都被接受,但db回滚并且没有保存(使用guard)。消息是:' attachments.attachable_id' =>'不能为空白'。我需要将它作为相关表的外键,并且必须与attachment_type一起保存。这就是我所拥有的:

class ReportsController < ApplicationController

def new
  @report = Report.new
  @report.attachments.build(attachable_id: @report.id)
end

def create
  @report = Report.new(params)
  @report.attachments.build                   

  respond_to do |format|
    if @report.save
      format.html { redirect_to @report, notice: 'Report was successfully created.' }
      format.json { render json: @report, status: :created, location: @report }
    else
      format.html { render action: "new" }
      format.json { render json: @report.errors, status: :unprocessable_entity }
    end
  end
end

private

def report_params
  params.require(:report).permit(:filing_year, :filing_number, :order_number, :location, :environmental_review,:biological_review, :cultural_review, :date_received, :status, attachments_attributes: [:id, :attachable_id, :attachable_type, :attachment])
  end
end

对于模特:

class Attachment < ActiveRecord::Base
  belongs_to :attachable, polymorphic: true
  validates :attachable_id, :attachable_type, presence: true
  do_not_validate_attachment_file_type :attachment

  Paperclip.interpolates :attached_to do |attachment, style|
    attachment.instance.attachable.class.to_s.downcase
  end

  has_attached_file :attachment,
                :url => "/attachments/:id/:basename.:extension",
                :path => ":rails_root/public/attachments/:attached_to/:id/:basename.:extension",
                :default_url => "/attachments/original/no-file.txt"

end

class Report < ActiveRecord::Base
  has_one :environmental_review
  has_many :attachments, as: :attachable
  accepts_nested_attributes_for :attachments

  validates :order_number, presence: true
  .
  .
  .
end

观看(苗条):

.report
  = form_for @report do |f|
    .
    .
    .
    = f.fields_for :attachments do |a|
      = a.file_field   :attachment
    .
    .
    .

谢谢。

1 个答案:

答案 0 :(得分:0)

对于您create方法中的一个,您再次致电@reports.attachments.build,但不要设置assignable_id,您需要这样做。您可以做的另一件事是添加一个名为attachable_id的隐藏表单字段。