簡體   English   中英

如何在 rake 任務中獲取 ActiveStorage 附件 URL?

[英]How to get the ActiveStorage attachment URL in a rake task?

我有一個 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

有沒有辦法在抽取任務中獲取附件的公共 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的主機,則還需要對其進行設置。

我浪費了很多時間尋找 get a file URL working on a Module file,但答案如下:

如果您需要從控制器/視圖上下文(后台作業、Cronjobs 等)外部創建鏈接,您可以像這樣訪問 rails_blob_path:

Rails.application.routes.url_helpers.rails_blob_path(user.avatar, only_path: true)

我在這個鏈接上建立了這個Redirect Mode:: Active Storage

我最終編寫了我自己的自定義控制器,用於永久鏈接到我在 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM