加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails Paperclip Gem – 将父模型ID保存到路径

发布时间:2020-12-17 02:25:21 所属栏目:百科 来源:网络整理
导读:我有一个ThreesixtyViewer模型,它也有ThreesixtyViewer Image模型的嵌套资源.正在通过 paperclip gem保存图像属性 – 但是我在更新文件路径时遇到了问题. 每个ThreesixtyViewer的图像需要一起保存在与特定查看器关联的一个目录中.例如: /public/system/thre
我有一个ThreesixtyViewer模型,它也有ThreesixtyViewer Image模型的嵌套资源.正在通过 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 …现在我在其中添加了一个:VIEWER_ID.

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

解决方法

您可以将任何模型属性添加到此对象的该路径中.我相信你甚至可以添加方法将响应的任何东西,所以你甚至可以创建路径助手来返回特定的字符串(例如保存月份,年份等).

在您的情况下,ThreesixtyViewerImage是一个子模型,您的表应包含父模型的列.在您的情况下,该属性可能是:threesixty_viewer_id

以下是我认为您在threesixty_viewer_image.rb上设置该路径所需的内容:

has_attached_file :image,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

任何时候你想要路径中的另一个属性,只需添加另一个插补器!再次抱歉误导你.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读