andrzej541
andrzej541

Reputation: 961

Rails paperclip default image only under certain conditions

I've got a Lead model which is splited by lead_status param on products and offers. Only leads with product status should contain images and offers should not. I've migrated attached product_image table to schema and tried to set a default image only for products. Like this:

class Lead < ApplicationRecord


has_attached_file :product_image, styles: { small: "150x150>", default: "350x350"}
validates_attachment_content_type :product_image, content_type: /\Aimage\/.*\z/

before_save :product_image_default_url

 def product_image_default_url
    if self.lead_status == "product" && self.product_image.url.nil?
      self.product_image.url = "/images/:style/default_user_avatar.png"
 end
end
  1. Every time when I save a new lead without uploaded image I get "/product_images/original/missing.png" as a default url. No matter which status it has.
  2. Model doesn't recognize new leads by it's status

How can I change that? Force my Lead model to save a default image url according to a "product" status and ignore all those with "offer" status?

My rails version is 5.2.1 and paperclip 6.0.0

Upvotes: 0

Views: 210

Answers (1)

ray
ray

Reputation: 5552

Try with following,

has_attached_file 
  :product_image, 
  styles: { small: "150x150>", default: "350x350"},
  default_url: ":style/default_user_avatar.png"

  # app/assets/images/medium/default_user_avatar.png
  # app/assets/images/thumbs/default_user_avatar.png

Existing method is,

def default_url
  if @attachment_options[:default_url].respond_to?(:call)
    @attachment_options[:default_url].call(@attachment)
  elsif @attachment_options[:default_url].is_a?(Symbol)
    @attachment.instance.send(@attachment_options[:default_url])
  else
    @attachment_options[:default_url]
  end
end

In initializer, Provide monkey patch for following,

require 'uri'
require 'active_support/core_ext/module/delegation'

module Paperclip
  class UrlGenerator

    def default_url
      if @attachment.instance.lead_status == 'product'
        default_url = attachment_options[:default_url]
      else
        default_url = # provide another missing default_url
      end 
      if default_url.respond_to?(:call)
        default_url.call(@attachment)
      elsif default_url.is_a?(Symbol)
        @attachment.instance.send(default_url)
      else
        default_url
      end
    end

  end
end

Update as per cases

Upvotes: 1

Related Questions