Delete Carrierwave File

Again I need your help. Now I need to understand how I can remove Carrierwave with downloadable files (in my case, images).

models / attachment.rb:

class Attachment < ActiveRecord::Base belongs_to :attachable, :polymorphic => true attr_accessible :file, :file mount_uploader :file, FileUploader end 

models / post.rb:

 class Post < ActiveRecord::Base attr_accessible :content, :title, :attachments_attributes, :_destroy has_many :attachments, :as => :attachable accepts_nested_attributes_for :attachments end 

* views / posts / _form.html.erb: *

 <%= nested_form_for @post, :html=>{:multipart => true } do |f| %> <% if @post.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2> <ul> <% @post.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div id="field"> <%= f.label :Nosaukums %>:<br /><br /> <%= f.text_field :title %><br /><br /> </div> <div id="field"> <%= f.label :Raksts %>:<br /><br /> <%= f.text_area :content %><br /><br /> </div> <%= f.fields_for :attachments do |attachment| %> <% if attachment.object.new_record? %> <%= attachment.file_field :file %> <% else %> <%= image_tag(attachment.object.file.url) %> <%= f.check_box :_destroy %> <% end %> <% end %> <%= f.submit "PublicΔ“t", :id => "button-link" %> <% end %> 

When I try to delete the previous downloaded file, I have this error:

 unknown attribute: _destroy 

Perhaps there is a problem because I have several file uploads, not just one.

+4
source share
4 answers

You are calling a method on the wrong model. Your file mount is located in the application.

The error tells you what is wrong.

 undefined method 'remove_file' for #<Post:0x471a320 

The key point of the error is that the method is called in the Post model when it needs to be called in the Attachment model.

Perhaps try looking at the checkbox for the correct model.

 <%= attachment.check_box :remove_file %> 
+3
source

None of this worked for me, but after digging I met this post that really helped. Mostly...

Form (where f are your form objects):

 <%= f.check_box :remove_image %> 

Then, if you check the box and submit the form, you will receive the following error:

Unable to assign protected attributes: remove_image

This is easy to solve by simply adding remove_image to your attr_accessible list on the model. In the end, it will look something like this:

 class Background < ActiveRecord::Base attr_accessible :image, :remove_image belongs_to :user mount_uploader :image, BackgroundUploader end 

In my case, this is a background image that belongs to the user. Hope this helps :)

+9
source

According to docs, the flag should be called remove_file .

+4
source

This should be <% = attachment.check_box: _destroy%>

It works for me

+3
source

All Articles