2013-09-24 27 views
1

这是我upload.rb轨回形针上传自定义URL路径

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它正在工作。

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

回答

3

您应该使用Paperclip's interpolations来实现此功能。首先,在初始界定的插值开始:

# 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而不是仅仅是您在模型中定义的实例方法 - 回形针专用利用插值定义URL /路径声明中的动态变量。

+0

s现在尝试其post_id:post_id不是post_id的值 – overflow

+0

请参阅我的解决方案更新。 – zeantsoi

1

在我的模型之一,我有

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

这是从回形针维基采取Github上。