Handling paperclip attachments with the same name
Posted on Jun 16 in Ruby on Rails | (1) Comment
This quick post is about some Paperclip-related code that I see quite frequently that could cause problems. It’s easy to miss this stuff in development and then get major headaches later.
class User < ActiveRecord::Base has_attached_file :photo end class Product < ActiveRecord::Base has_attached_file :photo end
The trouble is that by default the attachments will be stored in /public/system/photos/RECORD_ID/original/FILENAME and this can get messy if you have several types of records with the same id putting photos there.
In the example above you could potentially get
/public/system/photos/1/original/my_new_profile_picture.jpg
/public/system/photos/1/original/some_product_picture.jpg
This could get even messier if User.id=1 decides to upload a photo called nice.jpg and Product.id=1 also has a photo called nice.jpg.
Luckily Paperclip makes it really easy to fix this without having to do something ugly like change the photo attribute to user_photo and product_photo.
class User < ActiveRecord::Base has_attached_file :photo, :path => ":rails_root/public/system/users/:attachment/:id/:style/:basename.:extension", :url => "/system/users/:attachment/:id/:style/:basename.:extension" end class Product < ActiveRecord::Base has_attached_file :photo, :path => ":rails_root/public/system/products/:attachment/:id/:style/:basename.:extension", :url => "/system/products/:attachment/:id/:style/:basename.:extension" end
This will produce the following urls
/public/system/users/photos/1/original/my_new_profile_picture.jpg
/public/system/products/photos/1/original/some_product_picture.jpg
Comments
Thank you for your solution.
Leave a Comment