Rails:Paperclip 4 - 在创建过程中重命名文件

时间:2016-09-18 13:29:27

标签: ruby-on-rails ruby paperclip

我有一个带有Paperclip 4的Rails应用程序,其中有带图像的产品。现在,我希望在上传图像后将图像重命名为产品名称。

e.g。

产品:Really tasty sandwich 图片:really-tasty-sandwich-1.png

最后的数字应该等于产品所拥有的图像数量。

我尝试过插补器但是它们并不适用于我的情况,因为我希望第一个图像被调用really-tasty-sandwich-1.png而第二个really-tasty-sandwich-2.png,但内插器会更改为really-tasty-sandwich-2.png因为它是动态的。每个产品的图像数量可通过product.images.count获得,因为它是一个单独的模型。

所以我需要的是一些重命名图像的逻辑,这样用户就可以上传任意名称的图像,并且可以正确地重命名。

有人知道它是如何工作的吗?我猜可能是回调的东西。

由于

编辑:

到目前为止我的图像模型逻辑:

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

0 个答案:

没有答案