Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CarrierWave not saving upload after form redisplay

I have a rails app which originally used Paperclip for file uploads, however, as I saw that CarrierWave apparently had a 'persistant upload' type feature over form redisplays, I decided to give that a try.

In my view I have the following:

= f.input :attachment
= f.hidden_field :attachment_cache

Which correctly caches the file if the form fails validation and is redisplayed, however when I correct the validation errors and resubmit, the attachment is not processed.

Started POST "/section/model" for 127.0.0.1 at 2012-03-20 08:51:56 +0000
  Processing by Client::WishesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"zkdPQBsAnsNzx555rkwZ5+clfnLaXg+NtL+GdFei188=", "model"=>{"title"=>"Sample", "content"=>"Sample content", "contact_name"=>"Mr Sample", "contact_email"=>"[email protected]", "attachment_cache"=>"20120320-0851-42559-1644/SampleAttachment.pdf"}, "commit"=>"Create Wish"}
  Client Load (0.3ms)  SELECT `clients`.* FROM `clients` WHERE `clients`.`id` = 1 LIMIT 1
   (0.2ms)  BEGIN
  SQL (0.4ms)  INSERT INTO `models` (`attachment`, `client_id`, `contact_email`, `contact_name`, `content`, `created_at`, `status`, `title`, `updated_at`, `upload_content_type`, `upload_file_name`, `upload_file_size`, `upload_updated_at`) VALUES (NULL, 1, '[email protected]', 'Mr Sample', 'Sample content', '2012-03-20 08:51:56', 'Unresolved', 'Sample', '2012-03-20 08:51:56', NULL, NULL, NULL, NULL)

It appears to be correctly passing the attachment via the attachment_cache in the params, but it isn't then saving the attachment as it doesn't have a params[:model][:attachment] field.

It doesn't say any further steps on the carrierwave section for making uploads work across form redisplays on the CarrierWave GitHub.

like image 590
HaaR Avatar asked Mar 20 '12 09:03

HaaR


2 Answers

It's a bit of an old question, but it worked for me after I added the strong parameter to the controller, like this:

#controller
def object_params
  params.require(:object).permit(:attachment, :attachment_cache)
end

#view
<%= f.file_field :attachment %>
<%= f.hidden_field :attachment_cache %>
like image 126
Marko Ćilimković Avatar answered Sep 19 '22 10:09

Marko Ćilimković


Try populating the value of avatar_cache so that when validation fails, it will be pre-populated in the form:

= f.hidden_field :attachment_cache, :value => @model.attachment_cache

Where @model is the name of your model

This seems to work for me when the same form is reloaded multiple times (i.e. when validation fails multiple times). I think they left this out of the documentation.

like image 25
Kenny Avatar answered Sep 22 '22 10:09

Kenny