1

这是我的上传.rb

class Upload < ActiveRecord::Base
      belongs_to :post
      has_attached_file :upload,styles: { medium: ["500x400>",:jpg], thumb: ["100x100>",:jpg]},url: "/post_images/post_:postid/:style/:filename"

def postid
      self.post_id
end
end

我有一个带有 post_id 的列。正如所belongs_to代表的那样,我将为一篇文章提供不止一张图片。但是在将文件保存在文件夹而不是post_25. 它存储为post_:postid

但是,如果我按照:id它的工作方式给予。

我该如何解决。有人能帮忙吗。

4

2 回答 2

3

您应该使用Paperclip 的插值来实现此功能。首先,首先在初始化器中定义插值:

# config/initializers/interpolations.rb
Paperclip.interpolates :postid do |attachment, style|
  'post_' + attachment.instance.post.id
end

然后,您可以:postid直接在附件 URL 声明中使用插值(请记住先重新启动服务器):

# app/models/upload.rb
has_attached_file :upload,styles: { medium: ["500x400>",:jpg], thumb: ["100x100>",:jpg]},url: "/post_images/:postid/:style/:filename"

请注意,这:postid不仅仅是在模型中定义的实例方法——Paperclip专门利用插值来定义 URL/路径声明中的动态变量。

于 2013-09-24T17:21:07.823 回答
1

在我的一个模型中,我有

Paperclip.interpolates :invoice_file_name do |attachment, style|
  attachment.instance.invoice_file_name
end

取自 Github 上的 Paperclip wiki。

于 2013-09-24T18:42:38.103 回答