动态使用:Paperclip中的default_url

时间:2011-10-16 12:25:14

标签: ruby-on-rails paperclip

我正在尝试配置Paperclip,以根据实例的category属性提供不同的缺失图像。对象的每个类别都有自己的缺失图像。

这是我的第一次拍摄:

编辑以添加完整模型:

class Service < ActiveRecord::Base

  attr_accessible :logo, :logo_file_name, :logo_content_type, :logo_file_size, :logo_updated_at

  belongs_to :category, :counter_cache => true

  has_attached_file :logo,
                :path => "/:id-:style-:filename",
                :url  => ":s3_eu_url",
                :default_url => "/logos/:style/#{self.category.name]}.png",
                :styles => { :large => "600x400>",
                             :medium => "300x200>",
                             :small => "100x75>",
                             :thumb => "60x42>" }
end

class Category < ActiveRecord::Base
  attr_accessible nil

  has_many :services
end

在我看来,image_tag service.logo.url(:thumb)输出:

undefined method `category' for #<Class:0x0000010a731620>

有什么想法吗?

EDIT2:

有效的default_url是:default_url => "/logos/:style/missing.png",

解:

请参阅下面的答案。

4 个答案:

答案 0 :(得分:22)

我找到了一个解决方案,跟随this gist和另一个question in stackoverflow

我的工作解决方案:

Class Service

  has_attached_file :logo,
            :path => "/:id-:style-:filename",
            :url  => ":s3_eu_url",
            :default_url => :set_default_url_on_category,
            :styles => { :large => "600x400>",
                         :medium => "300x200>",
                         :small => "100x75>",
                         :thumb => "60x42>" }

  private

  def set_default_url_on_category
    "/logos/:style/#{category.name}.png"
  end
end

初始化程序paperclip_default_url_fix.rb

module Paperclip
  module Interpolations
    def self.interpolate(pattern, *args)
      pattern = args.first.instance.send(pattern) if pattern.kind_of? Symbol

      all.reverse.inject(pattern.dup) do |result, tag|
        result.gsub(/:#{tag}/) do |match|
          send(tag, *args)
        end
      end
    end
  end
end

答案 1 :(得分:9)

回形针wiki现在有一个很好的清洁解决方案,用于:url :路径,以及:default_url

https://github.com/thoughtbot/paperclip/wiki/Interpolations

答案 2 :(得分:8)

您可以将Proc as:default_url传递给paperclip。见https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/attachment.rb#L135。 Paperclip将使用Attachment对象作为参数调用该proc。 Attachment对象有一个访问者'instance',它是它所附加的ActiveRecord对象实例。在你的情况下,你应该:

  has_attached_file :logo,
            :path => "/:id-:style-:filename",
            :url  => ":s3_eu_url",
            :default_url => lambda { |attach| "/logos/:style/#{attach.instance.category.name]}.png },
            :styles => { :large => "600x400>",
                         :medium => "300x200>",
                         :small => "100x75>",
                         :thumb => "60x42>" }

答案 3 :(得分:0)

您不需要self

:default_url => "/logos/:style/#{category.name}.png",