【发布时间】:2017-03-28 11:45:03
【问题描述】:
我有一个使用 Paperclip 并将图像保存到 S3 的 Rails 应用程序。当用户上传没有图像的资产时,它会获取回形针设置中设置的默认图像。
我的 API 为这些资产提供服务,并在 JSON 响应中包含指向图像的链接(使用 jbuilder),但是我似乎无法返回默认图像 URL,它只返回“missing.png”,我希望它返回将整个 URL 连同缺失的图像路径一起返回给服务器。
我在模型中设置了默认 url,并且我尝试使用 ActionView::Helpers::AssetUrlHelper 来获取 image_url,但即使它在 rails 控制台内工作,它也无法正常工作。知道我可以做些什么来解决它吗?
JBuilder 文件:
json.profile_picture_smallest asset.profile_picture.url(:smallest)
json.profile_picture_small asset.profile_picture.url(:small)
json.profile_picture_medium asset.profile_picture.url(:medium)
json.profile_picture_large asset.profile_picture.url(:large)
json.profile_picture_original asset.profile_picture.url(:original)
模型中包含的回形针部分
module Picturable
extend ActiveSupport::Concern
included do
has_attached_file :profile_picture, path: '/images/' + name.downcase.pluralize + '/:style/:basename', default_url: "missing.png",
styles: {
smallest: '50x50>',
small: '100x100>',
medium: '200x200>',
large: '400x400>',
png: ['400x400>',:png]
}, :convert_options => {
smallest: '-trim',
small: '-trim',
medium: '-trim',
large: '-trim',
png: '-trim'
}
# Validate the attached image is image/jpg, image/png, etc
validates_attachment_content_type :profile_picture, :content_type => /\Aimage\/.*\Z/
end
def set_uuid_name
begin
self.profile_picture_file_name = SecureRandom.uuid
end while self.class.find_by(:profile_picture_file_name => self.profile_picture_file_name)
end
end
回形针配置:
Paperclip::Attachment.default_options[:s3_host_name] = 's3hostname'
开发配置:
config.paperclip_defaults = {
:storage => :s3,
:s3_credentials => {
:bucket => 'paperclipdev',
:access_key_id => 'accesskey',
:secret_access_key => 'secretaccesskey'
}
}
【问题讨论】:
-
请包含相关代码:jbuilder 视图、您的 Paperclip 配置等。
-
一种方法是在 s3 上上传
missing.png并将其 url 作为图像的默认值,因为您已经将 s3 用于其他文件。 -
我更新了问题。我知道这是一种方法,但我宁愿把它们放在铁轨内,有什么方法吗?