With paperclip, how can I change the image location to a “:parent_model_id/:id” folder format?

爱⌒轻易说出口 提交于 2019-12-03 13:13:50

问题


Given that I have a Listing model that has many images and each image has one attachment, how can I have the listing_id be part of the folder structure?

Like so: system/photos/[listing_id]/:id

I know that using :id will output the id of the image record.

Here's what I currently have:

class Image < ActiveRecord::Base
belongs_to :listing #Rails ActiveRecord Relation. An image belongs to a post. 

# paperclip data
has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :url => "/public/system/:class/:attachment/:id/:style_:filename"

end


回答1:


Ah, I finally figured it out. I needed to use Paperclip.interpolates.

This post from thoughtbot sort of explains it, but it's slightly outdated.

First, create a config/initializers/paperclip.rb file and add the following:

Paperclip.interpolates :listing_id do |attachment, style|
  attachment.instance.listing_id # or whatever you've named your User's login/username/etc. attribute
end

Which means that now in my images model I can refer to :listing_id like so:

class Image < ActiveRecord::Base
    belongs_to :listing #Rails ActiveRecord Relation. An image belongs to a post. 

    # paperclip data
    has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" }, 
    :url => "/system/:attachment/:listing_id/:id/:style_:filename" #location where to output the server. :LISTING_ID is defined in config/initializers/paperclib.rb

end

PS: You need to restart the server before the changes in initializers.rb take effect.




回答2:


you need to pass a url and path attribute. look at this thoughtbot blog post for help. The way you have it is close, but you need to pass the listing_id i would assume, not the :id.




回答3:


Since you've got a belongs_to relationship on your Image model, you should just be able to use listing_id as part of the paperclip config:

has_attached_file :photo, 
    :styles => { :medium => "300x300>", :thumb => "100x100>" }, 
    :url => "system/photos/:listing_id/:id"


来源:https://stackoverflow.com/questions/4546305/with-paperclip-how-can-i-change-the-image-location-to-a-parent-model-id-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!