如何获取存储在 Rails 控制器活动存储中的附件的 url [英] How can I get url of my attachment stored in active storage in my rails controller
问题描述
如何获取存储在 Rails 控制器活动存储中的 has_one 模型附件的 url.因此,我将能够将其作为 json 中的 api 的完整链接发送.到目前为止,我尝试了以下方法,但每种方法都存在各种问题:
How can I get url of my has_one model attachment stored in active storage in my rails controller. So, that I would be able to send it as full link as api in json. So far, I have tried following methods but each of them are giving various issues:
current_user.image.service_url
---- #<ActiveStorage::Attached::One:0x ....
current_user.image.service_url
---- undefined method `service_url' for #<ActiveStorage::Attached::One:0x....
Rails.application.routes.url_helpers.rails_disk_blob_path(current_user.image, only_path: true)
,它给了我这样的输出:
Rails.application.routes.url_helpers.rails_disk_blob_path(current_user.image, only_path: true)
, it gives me an output like:
/rails/blobs/%23%3CActiveStorage::Attached::One:0x007f991c7b41b8%3E"
"/rails/blobs/%23%3CActiveStorage::Attached::One:0x007f991c7b41b8%3E"
但这不是网址,对吗?我无法在浏览器上点击并获取图像.
but this is not a url, right? I am not able to hit and get image on browser.
url_for
----
未定义方法`active_storage_attachment_url' #<Api::V1::UsersController:0x007f991c1eaa98
undefined method `active_storage_attachment_url' for #<Api::V1::UsersController:0x007f991c1eaa98
推荐答案
使用方法rails_blob_path
用于控制器和模型中的附件
例如,如果您需要在控制器中分配一个变量(例如cover_url
),首先应该包含url_helpers
,然后使用方法rails_blob_path代码> 带有一些参数.你可以在任何模型、工人等中做同样的事情.
Use the method rails_blob_path
for attachements in a controller and models
For example, if you need to assign a variable (e.g. cover_url
) in a controller, first you should include url_helpers
and after use method rails_blob_path
with some parameters. You can do the same in any model, worker etc.
完整示例如下:
class ApplicationController < ActionController::Base
include Rails.application.routes.url_helpers
def index
@event = Event.first
cover_url = rails_blob_path(@event.cover, disposition: "attachment", only_path: true)
end
end
这篇关于如何获取存储在 Rails 控制器活动存储中的附件的 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!