Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carrierwave file delete

Again I need your help. Now I need to understand how I can delete with Carrierwave uploaded 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 am trying to delete previous uploaded file I have this error:

unknown attribute: _destroy

Maybe there is problem because I have multiple file uploads not only one.

like image 661
RydelHouse Avatar asked Feb 13 '13 14:02

RydelHouse


2 Answers

None of this worked for me, but after digging I came across this post that really helped. Basically...

Form (where f is your form objects):

<%= f.check_box :remove_image %>

Then, if you check the box and submit the form you'll get the following error:

Can't mass-assign protected attributes: remove_image

Which is easily solved by simply adding remove_image to your attr_accessible list on the model. In the end it'll look something like:

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

In my case it's a background image that belongs to the user. Hope this helps :)

like image 102
gbdev Avatar answered Oct 21 '22 16:10

gbdev


According to the docs, the checkbox should be called remove_file.

like image 28
Jiří Pospíšil Avatar answered Oct 21 '22 18:10

Jiří Pospíšil