我有一个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?
显然,.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
中的主机如果尚未设置,也需要设置。