如何在rake任务中获取ActiveStorage附件URL?

问题描述 投票:0回答:1

我有一个rake任务,在ActiveStorage存储图像。在同一个rake任务中,我需要这些图像的附件URL。

在正常的Rails上下文中,我使用url_for(my_attachment)。但是,帮助程序在rake任务中不可用。

我试图包括路线助手:

task my_task: :environment do
  include MyApp::Application.routes.url_helpers

  attachment = my_model.image.attach(..)
  url_for(attachment)
end

结果如下:

*** NoMethodError Exception: undefined method `attachment_url' for main:Object

有没有办法在rake任务中获取附件的公共URL?

ruby-on-rails rake-task rails-activestorage
1个回答
1
投票

显然,.attach(..)返回一个数组。以下工作:

task my_task: :environment do
  include MyApp::Application.routes.url_helpers

  attachment = my_model.image.attach(..).first

  Rails.configuration.default_url_options[:host] = 'localhost'
  url_for(attachment)
end

default_url_options中的主机如果尚未设置,也需要设置。

© www.soinside.com 2019 - 2024. All rights reserved.