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

时间:2018-03-04 18:05:33

标签: ruby-on-rails rake-task rails-activestorage

我有一个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?

2 个答案:

答案 0 :(得分:1)

显然,c1返回一个数组。以下工作正常:

.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 中的主机如果尚未设置,也需要设置。

答案 1 :(得分:0)

我最终为我在 rake 任务中使用的图像的永久链接编写了自己的自定义控制器。这看起来很hacky,但可能是预期的行为,我不确定。这可能会为某人节省大量时间:

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