Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 RC4 remove_attachment doesnt remove!

Using Carrierwave 0.5.4 on Rails 3.1 RC4.

In Rails console, I do:

@foo.attachment

returns:

=> http://cdn.site_name.com/uploads/users/2/banners/banner.png 

However:

@foo.remove_attachment!

returns:

 => [:remove_versions!] 

The record still remains in the DB, BUT the file is removed in the S3 bucket.

What is going on?

like image 745
Christian Fazzini Avatar asked Jan 19 '23 12:01

Christian Fazzini


1 Answers

Ahhh, after further investigating. This is what I have found out. remove_attachment! is meant to remove the image from S3, but is not meant to remove the uploader object in the attachment column, in the db. This is the normal behavior of Carrierwave.

Jnicklas provided a test spect at https://github.com/jnicklas/carrierwave/commit/ecabc618d0fce22c1931c6d2eb134886e3b60e4c which uses @doc.remove_image = true. This is the key, because when one submits a form to remove an attachment / image / photo / whatever. They normally include a check box that looks like:

<input type="checkbox" value="1" name="user[remove_attachment]" id="user_remove_attachment">

Which can be rendered with the helper tag as:

<%= f.check_box :remove_attachment %>

If the check box is clicked and the form is submitted. Params will look something like:

{"utf8"=>"✓", "_method"=>"put", ....., "user"=>{"remove_attachment"=>"1"}, "controller"=>"das....}

Rails will interpret this as @user.remove_attachment = true to clear the db column and also trigger .remove_attachment! to remove the file from S3. Also worth noting. If attr_accessible is defined in the User model. Then it must have :attachment, :remove_attachment as well.

Hope this helps someone out.

like image 93
Christian Fazzini Avatar answered Jan 31 '23 03:01

Christian Fazzini