user749798
user749798

Reputation: 5370

carrierwave cache not resubmitting

When I submit an image via Carrierwave, and am missing one field (i.e. the title), then the cached image will appear...

      <% if @post.avatar? %>
          <%= image_tag @post.avatar_url, :style => "width:300px"  %> 
          <%= f.hidden_field :avatar_cache %>
          <%= @post.avatar_url %>
      <% end %>

However, the :avatar_cache field is empty. When I resubmit the form, none of the image properties move forward, so I have to reselect the image.

The issue is similar to this. CarrierWave not saving upload after form redisplay but there was no answer.

What is happening? Thank you.

Upvotes: 10

Views: 3819

Answers (4)

Arctodus
Arctodus

Reputation: 5847

The carrierwave documentation is outdated for Rails 5+. Now that strong parameters are a part of Rails you have to white list avatar_cache in the controller. E.G:

params.require(:user).permit(:name, :avatar, :avatar_cache)

Also make sure you dont have attr_accessor :avatar_cache in model (that was my problem)

Upvotes: 0

stevenspiel
stevenspiel

Reputation: 5999

For me, the issue was that I had

accepts_nested_attributes_for :avatars, allow_destroy: true, reject_if: lambda { |avatar| avatar[:file].blank? }

So I was rejecting the file because the file wasn't there

It is important to note that the file itself does not persist, but only the file cache. That is why the carrierwave docs suggest:

It might be a good idea to show the user that a file has been uploaded, in the case of images, a small thumbnail would be a good indicator:

Upvotes: 5

Ivan Poliakov
Ivan Poliakov

Reputation: 2475

Check if you have an attr_accessor declaration for avatar_cache in your model. I added it by accident instead of attr_accessible (as mentioned in their docs) and it overrode the methods generated by CarrierWave.

Upvotes: 3

Kenny
Kenny

Reputation: 1151

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

<%= f.hidden_field :avatar_cache, :value => @post.avatar_cache %>

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.

Upvotes: -1

Related Questions