我有一个Lead模型,该模型按产品和报价中的lead_status参数进行了划分。仅具有产品状态的销售线索应包含图像,而报价不应包含。我已将附加的product_image表迁移到架构,并尝试仅为产品设置默认图像。像这样:
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
我该如何更改?强制我的Lead模型根据“产品”状态保存默认图片网址,而忽略所有具有“要约”状态的图片网址?
我的rails版本是5.2.1和回形针6.0.0
答案 0 :(得分:1)
尝试以下操作,
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
现有方法是
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
在初始化程序中,提供以下猴子补丁,
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
根据情况更新