BACKTRACE

(condense)

Back to Posts List

GET

Paperclip custom storage path

The :path definition in paperclip is basically an interpolated string, with a few tokens:

  • :rails_root – The path to the Rails application.
  • :rails_env – The current environment (e.g. development, production)
  • :class – The class name of the model that the attachment is part of, underscored and pluralised for your convenience.
  • :basename – The name of the originally uploaded file without its extension.
  • :extension – The file extension of the originally uploaded file.
  • :id – The ID of the model that the attachment is part of.
  • :id_partition – The same as :id but formatted as a string using ID partitioning.
  • :attachment – The name of the attachment attribute (defined in the call to has_attached_file) downcased and pluralised for your enjoyment.
  • :style – The current style of the attachment file being processed (e.g. in the ‘discarding an uploaded image‘ example above the :style would be one of ‘original’ or ‘small’)

But what if you want some other token? like and association id for example?

Let’s say we have a Photo that belongs_to an Album, and we want the album_id in out path.

First, we’ll add a custom token to our Paperclip installation. Create a file in config/initializers named paperclip_tokens.rb:


Paperclip::Attachment.interpolations[:photos_album_id] = proc do |attachment, style|
attachment.instance.album_id
end

attachment is out uploaded file, instance is the model instance which the uploaded file belongs to (Photo instance) and album_id is the attribute.

Than we can use it in our paperclip setup in the Photo model:


has_attached_file :picture,
:url => ‘/:attachment/:photos_album_id/:style/:basename.:extension’,
:path => ‘:rails_root/public/:attachment/:photos_album_id/:style/:basename.:extension’

win.

POST

blog comments powered by Disqus

I Don't have cookies.

ELAD ENV

Variable Value
LINKEDIN
TWITTER
FACEBOOK
GITHUB
WWR
IRC
{ 'irc.freenode.net' => [ '#rubyonrails', '#railsbridge', '#ruby', '#mootools' ]}
SKYPE
eladmeidar

You're seeing this error because I think it is funny.