首页 文章

将Paperclip用于嵌套模型

提问于
浏览
0

我正在尝试使用回形针将 Files 附加到 Log ,使用具有简单形式的嵌套表单 . 当文件是模型的属性时,我能够附加单个文件,但我需要能够将多个文件关联到日志(一对多),这就是为什么我现在有两个模型 . 我'm getting the following error but I'我不知道我错过了什么 .

找不到[#,@ original_filename =“1314e40ac73ab769790aea881730e12f.jpg”,@ content_type =“image / jpeg”,@ headers =“Content-Disposition:form-data; name = \”log [documents_attributes] [0] [附件] [] \“; filename = \”1314e40ac73ab769790aea881730e12f.jpg \“\ r \ nConContent-Type:image / jpeg \ r \ n”> ,, @ original_filename =“fsdfsdafsad-large.png”,@ content_type =“image / png“,@ headers =”Content-Disposition:form-data; name = \“log [documents_attributes] [0] [attachment] [] \”; filename = \“fsdfsdafsad-large.png \”\ r \ nContent -Type:image / png \ r \ n“>]

Document 型号:

class Document < ApplicationRecord
  default_scope { order(created_at: :desc) }

  belongs_to :log

  has_attached_file :attachment
  validates :log, presence: true
  validates_attachment_content_type :attachment, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end

Log 型号:

class Log < ApplicationRecord
  default_scope { order(created_at: :desc) }

  belongs_to :user
  belongs_to :server
  has_many :documents, dependent: :destroy
  accepts_nested_attributes_for :documents

  do_not_validate_attachment_file_type :documents
end

Log 控制器:

# GET /logs/new
  def new
    @log = Log.new
    @log.documents.build
  end

  # POST /logs
  # POST /logs.json
  def create
    @log = Log.new(log_params)

    if params[:documents_attributes]
      params[:documents_attributes].each do |doc|
        @log.documents.create(attachment: doc)
      end
    end

    #binding.pry
    respond_to do |format|
      if @log.save
        binding.pry
        format.html { redirect_to log_path(@log), notice: 'Log was successfully created.' }
        format.json { render :show, status: :created, location: @log }
      else
        format.html { render :new }
        format.json { render json: @log.errors, status: :unprocessable_entity }
      end
    end
  end

# Never trust parameters from the scary internet, only allow the white list through.
def log_params
  params.require(:log).permit(:user_id, documents_attributes: [:log_id, attachment: []])
end

Log 表单视图

<%= simple_form_for @log, html: { class: 'form-horizontal', enctype: 'multipart/form-data', local: true, multipart: true }   do |f| %>
  <%= f.simple_fields_for :documents, @log.documents do |ff| %>
    <%= ff.input :attachment, as: :file, input_html: { multiple: true } %>
  <% end %>
<% end %>

Update: 错误是在 Log 控制器的 create 操作中从 @log = Log.new(log_params) 触发的 .

1 回答

  • 0

    Paperclip旨在为每个'column'接受一个文件 . 您无法在 Document 的附件中添加多个文件 . 解决方案是要么找到另一个支持多个文件的gem(carrierwave将是最受欢迎的),要么创建一个属于__0000956_的新资源(例如 Attachment )并在那里添加 has_attached_file .

    PS:你得到的错误正在发生,因为你的 log_params 允许附件,期望它返回多个值,而回形针无法以这种方式处理附件 .

相关问题