Saving All Uploaded Attachments With Paperclip

Paperclip is available as an excellent gem to get started with image or attachments upload. It helps you get kick started with in a few minutes.

Include gem

gem 'papeclip'

Run bundle

bundle install

Add to your model

user.rb
1
2
3
4
5
6
7
8
class User < ActiveRecord::Base

  has_attached_file :attachment,
  :url => :attachment_url,
  :path => :attachment_path,
  :default_url => "/images/sheet.png"

end    

Setting custom path and url. for uploads can be checked out at my previous post.

By default when we try to upload any new image or attachment to the model, it deletes the previous uploaded attachment. There is a small option provided with paperclip that enables to save previous attachment even after uploading the new one. Add the following option

:preserve_files => false,

Add this to model,

user.rb
1
2
3
4
5
6
7
8
9
class User < ActiveRecord::Base

  has_attached_file :attachment,
  :preserve_files => false,
  :url => :attachment_url,
  :path => :attachment_path,
  :default_url => "/images/sheet.png"

end    

Now every attachment uploaded will be saved, without deleting the previous files. Soon, I will post another post how can we use this feature alongwith defining custom path and url for versioning the attachments.

Comments