Rails Active Storage:获取附件的相对磁盘服务路径

Rails Active Storage: Get relative disk service path for attachment

我正在切换到 Rails Active Storage 来处理产品目录的本地图像上传和存储(使用磁盘服务),但我无法获得可用的 url到图像以输入 <img> 标签。我在前端使用 React,所以我不能(轻松地)使用 Rails 助手来生成标签。

ActiveStorage 将文件放入 /public/images。我可以硬编码文件的相对链接(即 http://localhost:3000/images/Ab/CD/AbCDEfGhIjkL),它工作正常。

来自 Product.rb 的相关片段:

    class Product < ApplicationRecord
        attr_accessor :image_url
        has_one_attached :image

        def as_json(options)
            h = super(options)
            if self.image.attached?
                h[:image_url] = ActiveStorage::Blob.service.service_url(self.image.key)
            end
            h
        end
    end

as_json 生成一个 JSON 对象以提供给 React,该对象具有用于 <img>src 属性的条目 image_url。使用上面的代码,image_url 包含文件的 完整路径 (即 http://localhost:3000/srv/www/rails_app/public/images/Ab/CD/AbCDEfGhIjkL)。在视图中使用 url_for 会产生相同的结果。我希望它只包含相对于 rails root.

的路径

可以 操纵字符串以删除相对路径之前的所有内容,但我预见到如果有任何变化,这会在未来导致错误,所以我宁愿找到一个让 ActiveStorage 为我生成适当字符串的方法。

谢谢!

您需要使用路由助手为您的 Rails 应用构建 URL。

https://guides.rubyonrails.org/active_storage_overview.html#linking-to-files

class Product < ApplicationRecord
    attr_accessor :image_url
    has_one_attached :image

    def as_json(options)
        h = super(options)
        if self.image.attached?
            h[:image_url] = Rails.application.routes.url_helpers.rails_blob_path(self.image)
        end
        h
    end
end