Question

I'm using best_in_place to update the names of photos I've created with paperclip. The file name is being updated in the database but the file actually stored (/public/system/photos/attachments/...) isn't being updated to reflect the changed name.

The result is the app looking for the new file name that doesn't exist:

No route matches [GET] "/system/photos/attachments/000/000/011/original/new_file_name.jpg"

Photo controller:

def update
    @photo = Photo.find(params[:id])
    respond_to do |format|
      if @photo.update_attributes(photo_params)
        format.html { redirect_to(new_photo_path, :notice => 'Photo was successfully updated.') }
        format.json { respond_with_bip(@photo) }
      else
        format.html { render :action => "edit" }
        format.json { respond_with_bip(@photo) }
      end
    end
  end

Photo (new) view:

 <% @photos.each do |photo| %>
   <%= best_in_place photo, :attachment_file_name, :type => :input %>
 <% end %>
Was it helpful?

Solution

best_in_place is giving you mechanism to give a new name for your attachments whereas Paperclip is used for either uploading a new attachment or replacing with a new attachment. In your update action, you are passing a new attachment_file_name which will only update the file name of the attachment in the database but not the physical file name. In order to do that you'll have to rename the file using File.rename utility.

For example:

 def update
    @photo = Photo.find(params[:id])
    original_file_path = @photo.attachment.path
    folder_path = original_file_path.gsub(@photo.attachment_file_name,"")

    respond_to do |format|
      if @photo.update_attributes(photo_params)
        unless @photo.attachment.path == original_file_path
          File.rename(original_file_path, folder_path + @photo.attachment_file_name )
        end
        format.html { redirect_to(new_photo_path, :notice => 'Photo was successfully updated.') }
        format.json { respond_with_bip(@photo) }
      else
        format.html { render :action => "edit" }
        format.json { respond_with_bip(@photo) }
      end
    end
  end

Hope this resolves your issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top