如何在我的rails控制器中获取存储在活动存储中的has_one模型附件的URL。所以,我可以在json中将其作为api的完整链接发送。到目前为止,我尝试了以下方法,但每个方法都提出了各种问题:
1)current_user.image.service_url ----未定义的方法`service_url'for#
2)Rails.application.routes.url_helpers.rails_disk_blob_path(current_user.image,only_path:true),它给我一个输出,如:
"/rails/blobs/%23%3CActiveStorage::Attached::One:0x007f991c7b41b8%3E"
但这不是网址,对吗?我无法在浏览器上点击并获取图像。
3)url_for ----
undefined method `active_storage_attachment_url' for #<Api::V1::UsersController:0x007f991c1eaa98
rails_blob_path
for attachements in a controller and models例如,如果您需要在控制器中分配变量(例如cover_url
),首先应该包括url_helpers
,并在使用方法rails_blob_path
之后添加一些参数。您可以在任何模型,工人等中执行相同的操作。
完整示例如下:
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活动存储,但我在文档中读到的这可能对你有帮助
试试rails_blob_url(model.image)
更多http://edgeguides.rubyonrails.org/active_storage_overview.html
有时,例如API需要为客户端(例如移动电话等)返回具有主机/协议的完整URL。在这种情况下,将host参数传递给所有rails_blob_url调用是重复的而不是DRY。甚至,您可能需要在dev / test / prod中使用不同的设置才能使其正常工作。
如果您正在使用ActionMailer并且已经在环境/ * .rb中配置了该主机/协议,则可以使用rails_blob_url
或rails_representation_url
重用该设置。
# in your config/environments/*.rb you might be already configuring ActionMailer
config.action_mailer.default_url_options = { host: 'www.my-site.com', protocol: 'https' }
我建议只调用完整的Rails.application.url_helpers.rails_blob_url
,而不是将至少50种方法转储到模型类中(取决于你的routes.rb),当你只需要2时。
class MyModel < ApplicationModel
has_one_attached :logo
# linking to a variant full url
def logo_medium_variant_url
variant = logo.variant(resize: "1600x200>")
Rails.application.routes.url_helpers.rails_representation_url(
variant,
Rails.application.config.action_mailer.default_url_options
)
end
# linking to a original blob full url
def logo_blob_url
Rails.application.routes.url_helpers.rails_blob_url(
logo.blob,
Rails.application.config.action_mailer.default_url_options
)
end
end
我能够使用以下内容在浏览器中查看图像:
<%= link_to image_tag(upload.variant(resize: "100x100")), upload %>
upload
是附图。