Rails的回形针宝石 - 父模型ID保存路径
我有ThreesixtyViewer也有ThreesixtyViewerImage模型嵌套资源的典范。图像属性正在通过paperclip gem保存 - 但我在更新文件路径时需要如何解决问题。Rails的回形针宝石 - 父模型ID保存路径
需要将每个ThreesixtyViewer的图像一起保存到与特定查看器关联的一个目录中。例如:
/public/system/threesixty_viewer_images/12/large/filename.jpg
在这个例子中,在路径中将是具体threesixtyviewer的ID - 但我无法找到该功能的任何实例。如果ThreesixtyViewer为57的ID,那么路径看起来像这样:
/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/
我知道:路径和:url属性需要更新编辑为threesixty_viewer_image.rb内has_attached_file - 但我不确定如何可以得到threesixty_viewer的ID ...现在我在它的位置添加了一个:VIEWER_ID。
任何帮助将不胜感激!预先感谢任何可以借鉴的人!
您可以将任何模型属性添加到该对象的该路径。我相信你甚至可以添加任何方法将会响应的东西,所以你甚至可以创建路径助手来返回特定的字符串(比如它保存的月份,年份等)。
对你而言,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
。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
无论何时您想要路径中的其他属性,只需添加另一个插补器!对不起,以前误导你。
@colin_hagan
是正确的道路上 - 我建议你看看Paperclip 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
。
这照顾它谢谢! paperclip_defaults也是一个很好的提示,一定会在我的下一个项目中使用它!再次感谢! –
当我用**:threesixty_viewer_id **或任何其他应该可用的属性(即:article_id)执行此操作时 - 它将目录保存为完全一样的...所以它现在看起来像'/ public/system/threesixty_viewer_images /:threesixty_viewer_id/large/filename.jpg' –
更新了我的回答,并提供了有关插值以及如何使用它们的更多具体细节。 –