首页 文章

使用基于多态模型属性的回形针创建不同样式的图像附件?

提问于
浏览
1

我正在使用多态图片模型将图像与User,Place等其他模型相关联 .

作为回形针文档,图片模型可以使用以下方法定义一组样式:

has_attached_file:avatar,:styles => {:medium =>“300x300>”,:thumb =>“100x100>”}

但是作为多态并与不同模型相关联,每个条目所需的样式将是不同的 . 要解决此问题,我如何动态设置自定义样式?

1 回答

  • 0

    我们使用的是你所指的东西 .

    我们在 config/application.rb 文件中设置Paperclip defaults

    #config/application.rb
    ...
    
    config.paperclip_defaults = {
       styles: { :large => "x850", :medium => "x450", :thumb => "x200"},
       default_url: "layout/placeholders/:style/placeholder.png"
    }
    

    这将设置一组默认样式,可以在模型本身中覆盖这些样式 .

    然后我们使用 asset 模型(带有相应的DB)来保存所有数据 . 然后,此 asset 模型将 url 方法(对于Paperclip)委托给其依赖模型 .

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    多态关联的原始代码是here .

    由于Paperclip样式是默认值,因此您可以根据需要在任何相关模型中覆盖它们 .

相关问题