Rails Paperclip Gem - 将父模型ID保存到路径

时间:2015-12-08 19:42:22

标签: ruby-on-rails ruby ruby-on-rails-4 paperclip

我有一个 ThreesixtyViewer 模型,它还有 ThreesixtyViewerImage 模型的嵌套资源。正在通过paperclip gem保存图片属性 - 但我在更新文件路径方面遇到了问题。

每个 ThreesixtyViewer 的图像需要一起保存在与特定查看器关联的一个目录中。例如:

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

在此示例中,路径中的 12 将是特定threesixtyviewer的ID - 但我找不到具有该功能的任何示例。如果 ThreesixtyViewer 的ID为57,那么路径将如下所示:

/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/

我知道:path和:url属性需要针对 threesixty_viewer_image.rb 中的has_attached_file进行更新 - 但我不确定如何获取threesixty_viewer的id ... for现在我在其中添加了一个:VIEWER_ID。

任何帮助将不胜感激!提前感谢任何能够吸引眼球的人!

2 个答案:

答案 0 :(得分: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::InterpolationHere's a link

以下是我的使用方法:

  1. 创建新文件:config/initializers/paperclip_interpolators
  2. 将这样的内容放在该文件中:

    Paperclip.interpolates :threesixty_viewer_id do |attachment, style|
      attachment.instance.threesixty_viewer_id
    end
    
  3. 重新启动您的应用
  4. 重新生成附件的路径/文件夹。 Here's a Link
  5. 只要您想在路径中使用其他属性,只需添加另一个插补器即可!再次抱歉误导你。

答案 1 :(得分:1)

MainComponent走在正确的道路上 - 我建议你研究一下Paperclip Interpolations

public string JsonPropertyName
{
    get
    {
        var resolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
        return resolver.GetResolvedPropertyName(PropertyName);
    }
}

注意双引号,而不是单引号。

双引号应该用于插值 - 单引号用于文字字符串(我认为)。

我发现回溯的另一件事是paperclip_defaults选项 - 允许您为任何附件指定@colin_hagan等:

#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

这些可以在您的相应模型中覆盖 - 它对我来说非常方便,因为这意味着您每次有附件时都不必明确定义styles