Rails: Paperclip 4 - Renaming a file during creation
<p>I have a Rails application with Paperclip 4 where there are products with images. Now, I want after an image is uploaded to rename the image to the product name.</p>

<p>e.g.</p>

<p>Product: <code>Really tasty sandwich</code>
Image: <code>really-tasty-sandwich-1.png</code></p>

<p>The number at the end should be equal to the amount of images which the product possesses.</p>

<p>I tried interpolators but they don't really work for my case since I want the first image to be called <code>really-tasty-sandwich-1.png</code> and the second <code>really-tasty-sandwich-2.png</code> but interpolators changes both to <code>really-tasty-sandwich-2.png</code> since it is dynamically. The amount of images per product is available through <code>product.images.count</code> since it is a separate model.</p>

<p>So what I need is some logic which renames the image so a user can upload an image with whatever name he wants and it will be renamed correctly.</p>

<p>Does somebody have an idea how it works? Probably something with callbacks I guess.</p>

<p>Thanks</p>

<p>Edit:</p>

<p>My image model logic so far:</p>

<pre><code>has_attached_file :image,
                path: ':rails_root/public/product_images/:attachment/:id_partition/:normalized_filename',
                url: '/product_images/:attachment/:id_partition/:normalized_filename'

Paperclip.interpolates :normalized_filename do |attachment, style|
  if attachment.instance.product.present?
    attachment.instance.normalized_filename(attachment.content_type)
  else
    attachment.original_filename
  end
end

def normalized_filename(content_type)
  "#{product.name.downcase.split(' ').join('-')}-#{product.images.count}.#{content_type.split('/').last}"
end
</code></pre>