Rails 3 - How to Replace an Existing Paperclip Application

I have an invoice model. When I create an invoice, an attachment is required. It works.

How to replace the application during the update? I want the original attachment to be deleted. When I have the same form field on the edit screen, it does not update after submitting. The old file still exists. In addition, it displays “file not selected”, although it is. I can click on the View Attachment and display it just fine.

invoice.rb

has_attached_file :attachment, :url => "http://...../attachments/:id/:style/:basename.:extension", :path => ":rails_root/public/attachments/:id/:style/:basename.:extension" validates_attachment_presence :attachment validates_attachment_size :attachment, :less_than => 5.megabytes 

_form.html.erb

 <label>Invoice Attachment: </label> <%= f.file_field :attachment %> <%= link_to 'View Attachment', @invoice.attachment.url %> 
+4
source share
1 answer

All you have to do is call update_attributes or the equivalent, and the clip will automatically delete the old attachment. For example, let's say you have this form (from paperclip docs ):

 <%= form_for @user, :url => users_path, :html => { :multipart => true } do |form| %> <%= form.file_field :avatar %> ... <% end %> 

In your controller, you might have something like the following:

 def update @user = User.find(params[:id]) @user = User.update_attr(params) end 

Or, if you want to update the attachment, you can do this:

 def update @user = User.find(params[:id]) avatar_data = params.slice('avatar') @user = User.update_attr(avatar_data) end 

In any case, the old attachment will be deleted from the repository, and the new file will take its place.

0
source

Source: https://habr.com/ru/post/1447029/


All Articles