【问题标题】:Rails Active Storage: Get relative disk service path for attachmentRails Active Storage:获取附件的相对磁盘服务路径
【发布时间】:2019-09-17 01:56:09
【问题描述】:

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

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

来自Product.rb的相关sn-p:

    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,该对象具有一个条目 image_url,用于 &lt;img&gt;src 属性。使用上面的代码,image_url 包含文件的完整路径(即http://localhost:3000/srv/www/rails_app/public/images/Ab/CD/AbCDEfGhIjkL)。在视图中使用url_for 会产生相同的结果。我希望它只包含相对于 rails root 的路径。

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

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby reactjs rails-activestorage


    【解决方案1】:

    您需要使用 routes 帮助器来构建您的 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
    

    【讨论】:

    • 谢谢!我试过了,但遇到了另一个错误。我使用stackoverflow.com/questions/7219732/… 的解决方案解决了这个问题,结合它现在可以工作了。
    • 不错!哦,如果 React 应用程序与 Rails 应用程序托管在同一个域上,你总是可以将 only_path: true 添加到 rails_blob_path 方法调用中。然后它会生成不包含域的 URL。例如:/images/Ab/CD/AbCDEfGhIjkL
    猜你喜欢
    • 2020-11-04
    • 2022-11-28
    • 2018-10-24
    • 1970-01-01
    • 2011-07-09
    • 2017-02-11
    • 2019-12-26
    • 1970-01-01
    • 2019-08-16
    相关资源
    最近更新 更多