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

前端 未结 3 1527
太阳男子
太阳男子 2021-02-06 07:42

Given that I have a Listing model that has many images and each image has one attachment, how can I have the

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-06 08:09

    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.

提交回复
热议问题