在附件的嵌入式文档路径中使用父 ID

Using parent ids in the embedded document path for an attachment

我想将附件保存在如下路径中:

rails_root/parent/:id_parent/child/:id_child/:文件名

class Parent
  include Mongoid::Document
  embeds_many :childrens , cascade_callbacks: true
end

class Child
  include Mongoid::Document
  include Mongoid::Paperclip
  embedded_in :parent, inverse_of: :childrens
  has_mongoid_attached_file :photo,
       path: "parent/:id_parent/child/:id/:filename"
end

如何使用 :id_parent?因为现在是未定义的,它应该有父 ID 值。

插值:https://github.com/thoughtbot/paperclip/wiki/Interpolations

class Child
  include Mongoid::Document
  include Mongoid::Paperclip
  embedded_in :parent, inverse_of: :childrens
  has_mongoid_attached_file :photo,
       path: "parent/:id_parent/child/:id/:filename"

  Paperclip.interpolates :id_parent do |attachment, style|
    return attachment.instance.parent.id.to_s
  end

end