Reputation: 10009
I have a form that I create a Project in. A Project may have many Attachments. An Attachment has a DocumentUploader mounted. But when I submit the form, the uploaded file is not attached to the Attachment i create. Any idea what might be wrong? I'm able to add documents to attachments when I'm testing from console.
the form
66 .field
67 = f.label :attachment, 'Velg vedlegg'
68 = file_field_tag "attachments[]", type: :file, multiple: true
controller
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}"
from the logs
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
testing with Better Errors
>> 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
Upvotes: 0
Views: 1059
Reputation: 13611
Be sure you have multipart set to true in a form that has any file attachments. Example:
= form_for [@post], html: { multipart: true } do |f|
.field
= f.text_field :title
.field
= f.file_field :image_attachment
Upvotes: 1