Handling paperclip attachments with the same name

by Monica Olinescu on June 16, 2010

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.

[code lang='ruby']

class User < ActiveRecord::Base

has_attached_file :photo

end

class Product < ActiveRecord::Base

has_attached_file :photo

end

[/code]

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.

[code lang='ruby']

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

[/code]

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

One comment

Thank you for your solution.

by datnt on June 17, 2010 at 9:30 pm. #

Leave your comment

Required.

Required. Not published.

If you have one.