【问题标题】:Getting URL for public assets in Rails model在 Rails 模型中获取公共资产的 URL
【发布时间】: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 用于其他文件。
  • 我更新了问题。我知道这是一种方法,但我宁愿把它们放在铁轨内,有什么方法吗?

标签: ruby-on-rails paperclip


【解决方案1】:

我认为这样做的方法是在您的 jbuilder 文件中使用资产助手:

json.profile_picture_smallest asset_url(asset.profile_picture.url(:smallest))

这里值得一提的是,如果您希望默认 url 基于模型是动态的,您还可以将符号方法名称传递给回形针的 default_url 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 2017-01-04
    相关资源
    最近更新 更多