简体   繁体   English

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

[英]Rails Active Storage: Get relative disk service path for attachment

I'm switching to Rails Active Storage to handle upload and storage of images locally (using the disk service) for a product catalog, and I'm having trouble getting a usable url to the image to feed into an <img> tag. 我正在切换到Rails Active Storage来为产品目录本地处理(使用磁盘服务)图像的上载和存储,并且在获取图像的可用URL以馈入<img>标记时遇到了麻烦。 I'm using React on the frontend, so I can't (easily) use Rails helpers to generate the tag. 我在前端使用React,所以我不能(轻松地)使用Rails助手来生成标签。

ActiveStorage puts the files in /public/images . ActiveStorage将文件放在/public/images I can hardcode relative links to the files (ie http://localhost:3000/images/Ab/CD/AbCDEfGhIjkL ) and it works fine. 我可以对文件的相对链接进行硬编码(即http://localhost:3000/images/Ab/CD/AbCDEfGhIjkL ),并且可以正常工作。

Relevant snippet from Product.rb : 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 produces a JSON object to feed to React that has an entry image_url that is used for the <img> 's src attribute. as_json生成一个JSON对象以馈送到React,该对象具有用于<img>src属性的image_url条目。 With the code above, image_url contains the full path to the file (ie http://localhost:3000/srv/www/rails_app/public/images/Ab/CD/AbCDEfGhIjkL ). 使用上面的代码, image_url包含文件的完整路径 (即http://localhost:3000/srv/www/rails_app/public/images/Ab/CD/AbCDEfGhIjkL )。 Using url_for in the view produces the same result. 在视图中使用url_for会产生相同的结果。 I want it to only contain the path relative to rails root. 我希望它只包含相对于rails根的路径。

I could manipulate the string to remove everything before the relative path, but I foresee this causing bugs in the future if anything ever changes, so I'd much rather find a way to get ActiveStorage to just generate an appropriate string for me. 可以操纵该字符串以删除相对路径之前的所有内容,但是我预见到这会在将来发生任何变化的情况下引起错误,因此,我宁愿找到一种方法来使ActiveStorage仅为我生成一个合适的字符串。

Thanks! 谢谢!

You need to use the routes helper to build of a URL to your Rails app. 您需要使用路由助手来构建指向Rails应用程序的URL。

https://guides.rubyonrails.org/active_storage_overview.html#linking-to-files 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM