Rails Paperclip Gem - save parent model id to path

I have a ThreesixtyViewer model that also has a ThreesixtyViewerImage model nested resource . The image attribute is saved using paperclip gem - but I am having problems updating the file path as needed.

Images for each ThreesixtyViewer must be stored together in a single directory associated with a particular viewer. For example:

/public/system/threesixty_viewer_images/12/large/filename.jpg

In this example, 12 in the path will be the identifier of a specific threesixtyviewer, but I cannot find examples with this functionality. If ThreesixtyViewer has an identifier of 57, then the path will look like this:

/public/system/threesixty_viewer_images/57/large/filename.jpg

threesixty_viewer.rb

belongs_to :article

has_many :threesixty_viewer_images, dependent: :delete_all
accepts_nested_attributes_for :threesixty_viewer_images, allow_destroy: true

threesixty_viewer_image.rb

belongs_to :threesixty_viewer

has_attached_file :image, styles: { small: "500x500#", large: "1440x800>" },
  path: ':rails_root/public/system/:class/:VIEWER_ID/:size/:filename',
  url: '/system/:class/:VIEWER_ID/:size/:filename'
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/

I know that the attributes: path and: url should be updated for the has_attached_file file in threesixty_viewer_image.rb - but I'm not sure how I can get the identifier for threesixty_viewer ... for now I added: VIEWER_ID in this place.

Any help would be greatly appreciated! Thank you in advance to everyone who can lend their eyes.

+4
source share
2

. , -, , (, , , ..).

ThreesixtyViewerImage , . , , : threesixty_viewer_id

threesixty_viewer_image.rb:

has_attached_file :image, 
  styles: { small: "500x500#", large: "1440x800>" },
  path: ":rails_root/public/system/:class/:threesixty_viwer_id/:size/:filename",
  url: "/system/:class/:threesixty_viewer_id/:size/:filename"

validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/

, , . ! Paperclip::Interpolation.

, :

  • : config/initializers/paperclip_interpolators
  • - :

    Paperclip.interpolates :threesixty_viewer_id do |attachment, style|
      attachment.instance.threesixty_viewer_id
    end
    
  • / .

, , ! , .

+2

@colin_hagan - Interpolations :

#app/models/threesixty_viewer_image.rb
class ThreesixtyViewerImage < ActiveRecord::Base
   belongs_to :threesixty_viewer

   has_attached_file :image,
      path: ":rails_root/public/system/:class/:threesixty_viewer_id/:size/:filename",
      url: "/system/:class/:threesixty_viewer_id/:size/:filename"

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

, .

- ( ).


, , - paperclip_defaults - styles .. :

#config/application.rb
...
config.paperclip_defaults = { 
   styles: { small: "500x500#", large: "1440x800>" }
}

- , , styles , .

+1

Source: https://habr.com/ru/post/1619096/


All Articles