Rails CarrierWave:未保存上传的文件

时间:2014-08-27 11:51:35

标签: ruby-on-rails carrierwave

我有一个表单,我创建了一个项目。项目可能有很多附件。 附件已安装DocumentUploader。 但是当我提交表单时,上传的文件没有附加到我创建的附件中。知道什么可能是错的吗?当我从控制台测试时,我能够将文档添加到附件中。

表格

 66   .field
 67     = f.label :attachment, 'Velg vedlegg'
 68     = file_field_tag "attachments[]", type: :file, multiple: true

控制器

 53       if @project.update(project_params)
 54
 55         if params[:attachments]
 56           params[:attachments].each do |attachment|
 57             a = @project.attachments.create!(document: attachment)
 58             Rails.logger.debug "attachment as seen from the params hash: #{attachment}"
 59             Rails.logger.debug "attachment.document is #{a.document.inspect}"
 60             Rails.logger.debug "URL is nil #{a.document.url == nil}"
来自日志的

web.1  | Processing by Customers::ProjectsController#update as HTML
web.1  | Parameters: {"utf8"=>"✓", "authenticity_token"=>"XX=", 
         "project"=>{"name"=>"", "description"=>"", 
         "attachments"=>["Screen Shot 2014-04-13 at 21.18.34.png"],

web.1  | attachment as seen from the params hash: Screen Shot 2014-04-13 at 21.18.34.png
web.1  | attachment.document is #<DocumentUploader:0x007fad727003d8 
         @model=#<Attachment id: 17, document: nil, project_id: 4, 
         created_at: "2014-08-27 11:42:00", updated_at: "2014-08-27 11:42:00">,          
         @mounted_as=:document, @storage=#<CarrierWave::Storage::File:0x007fad761cef28 
         @uploader=#<DocumentUploader:0x007fad727003d8 ...>>>
web.1  | URL is nil true

project.rb

class Project < ActiveRecord::Base
has_many :attachments

attachment.rb

1 class Attachment < ActiveRecord::Base
2   mount_uploader :document, DocumentUploader
3 end

使用更好的错误进行测试

>> a
=> #<Attachment id: 21, document: nil, project_id: 4, created_at: "2014-08-27 12:57:42", updated_at: "2014-08-27 12:57:42">
>> a.document = attachment
=> "400.png"
>> a.save
=> true
>> a
=> #<Attachment id: 21, document: nil, project_id: 4, created_at: "2014-08-27 12:57:42", updated_at: "2014-08-27 12:58:10">
>> a.document.url
=> nil

1 个答案:

答案 0 :(得分:1)

确保在包含任何文件附件的表单中将multipart设置为true。例如:

= form_for [@post], html: { multipart: true } do |f|
  .field
    = f.text_field :title
  .field
    = f.file_field :image_attachment