我有一个360视图模型,它也有一个360视图图像模型的嵌套资源。图像属性正在通过paperclip gem保存,但我在如何更新文件路径时遇到问题。
每个360查看器的图像需要一起保存在与特定查看器关联的一个目录中。例如:
/public/system/threesixty_viewer_images/12/large/filename.jpg
在本例中,路径中的12将是特定的360查看器的ID,但是我找不到任何具有该功能的示例。如果360号观众的ID是57,那么这条路看起来就是这样:
/public/system/threesixty_viewer_images/57/large/filename.jpg
360度浏览器.rb
belongs_to :article
has_many :threesixty_viewer_images, dependent: :delete_all
accepts_nested_attributes_for :threesixty_viewer_images, allow_destroy: true
360_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属性需要为360_viewer_image.rb中的has_attached_文件更新,但我不确定如何获取360_viewer的ID…现在我在它的位置添加了一个:viewer\u id。
任何帮助都将不胜感激!提前感谢所有能帮忙的人!
最佳答案
您可以将任何模型属性添加到此对象的路径中。我相信您甚至可以添加该方法将响应的任何内容,这样您甚至可以创建路径帮助器来返回特定的字符串(例如保存的月份、年份等)。
在您的例子中,ThreeSixtyViewerImage是一个子模型,您的表应该包含父模型的列。在你的例子中,这个属性可能是:360观众id
我认为您需要在360_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
。Here's a link以下是我利用的方法:
创建新文件:
config/initializers/paperclip_interpolators
把这样的东西放在文件里:
Paperclip.interpolates :threesixty_viewer_id do |attachment, style|
attachment.instance.threesixty_viewer_id
end
重新启动应用程序
重新生成附件的路径/文件夹。Here's a Link
只要你想在你的路径中有另一个属性,只需添加另一个插值器!再次抱歉之前误导了你。