Ruby on rails 如何在rake任务中获取ActiveStorage附件URL?
我有一个rake任务,它将图像存储在Ruby on rails 如何在rake任务中获取ActiveStorage附件URL?,ruby-on-rails,rake-task,rails-activestorage,Ruby On Rails,Rake Task,Rails Activestorage,我有一个rake任务,它将图像存储在ActiveStorage中。在同一个rake任务中,我需要这些图像的附件URL 在正常的Rails上下文中,我会使用url\u作为(我的附件)。但是,该助手在rake任务中不可用 我尝试包含路线辅助对象: task my_task: :environment do include MyApp::Application.routes.url_helpers attachment = my_model.image.attach(..) url_fo
ActiveStorage
中。在同一个rake任务中,我需要这些图像的附件URL
在正常的Rails上下文中,我会使用url\u作为(我的附件)
。但是,该助手在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\u url\u options
中的主机也需要设置。我最终为我在rake任务中使用的图像编写了自己的永久链接自定义控制器。这似乎有点骇人听闻,但我不确定是否是有意为之。这可能会为某人节省大量时间:
class ImageFilesController < ApplicationController
def show
mymodel = MyModel.find(params[:id])
send_data(
mymodel.name_of_attachment.blob.download,
type: mymodel.name_of_attachment.blob.content_type,
disposition: :inline
)
end
end
class ImageFileController