Paperclip deletes images with empty file fields update with rails 2.3

Bahhh! When you update a model that contains an empty file field in Rails 2.3 the attachment is deleted. It looks like empty file fields get passed as nil and then Paperclip gets angry.

Processing Admin::PostsController#update (for at 2009-03-05 01:21:08) [PUT]
  Parameters: {"commit"=>"Update", "post"=>{"title"=>"Post Title", "image"=>nil}, "id"=>"124"}

There are two quick monkey patches that I’ve been using, the first, was splitting off attachments to their own method (edit_attachment)…but this quickly became a nuisance. A quicker work around is to remove the attachment field, in this case “image”, from the parameters.

# PUT /posts/1
# PUT /posts/1.xml
def update
  @post = Post.find(params[:id])

  # delete the offending parameter
  params[:post].delete(:image) if params[:post][:image].nil?

  respond_to do |format|
    if @post.update_attributes(params[:post])
      flash[:notice] = 'Post was successfully updated.'
      format.html { redirect_to(admin_post_url(@post)) }
      format.html { render :action => "edit" }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>