Rails ActiveStorage 不保存在 ActiveJob 范围内执行的附件

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

我有一个 ActiveJob,它从 URL 下载图像并将其附加到 ActiveRecord 实例。在工作范围内,附件工作正常 - 我可以成功读回 blob。但是,当我尝试从控制台访问带有附件的同一记录时,未附加 blob。对我来说看起来像是 Rails bug。

这是工作代码:

require 'open-uri'

class DownloadJob < ActiveJobStatus::TrackableJob

  queue_as :default

  def perform(image)
    begin
      downloaded_image = URI.parse(image.url).open
      image.data.attach(io: downloaded_image, filename: image.filename)
      image.save
      puts "Attached: #{image.data.attached?}" # True
      puts "Filename: #{image.filename}" # Shows proper filename
      puts "Blob: #{image.data.download}" # Displays blob
      image.image_downloaded = true
      image.url_is_valid = true
    rescue StandardError => e
      puts "EXCEPTION!!! #{e}"
      image.url_is_valid = false
    end
    image.save
  end
end

以及控制台中执行的代码:

i = Image.second
j = DownloadJob.perform_later(i)
i.data.attached? # false
i.data.download # nil

我在项目的存储目录中看到下载的图像 blob。我在两个表中都看到它们:active_storage_blobs 和 active_storage_attachments。

我的图像模型具有自定义主键“url”,这可能是问题的原因,因为我无法识别哪些列rails引用了activestorage表中的模型实例

ruby-on-rails rails-activerecord rails-activestorage rails-activejob
1个回答
0
投票

我已经搞定了。问题确实是 ActiveRecord 的字符串主键。我已经修改了数据库迁移文件中的字段并且它起作用了。

更改此:

create_table :active_storage_attachments, id: primary_key_type do |t|
      t.string     :name,     null: false
      t.references :record,   null: false, polymorphic: true, index: false, type: :foreign_key_type
      t.references :blob,     null: false, type: foreign_key_type

      if connection.supports_datetime_with_precision?
        t.datetime :created_at, precision: 6, null: false
      else
        t.datetime :created_at, null: false
      end

      t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true
      t.foreign_key :active_storage_blobs, column: :blob_id
    end

对此:

create_table :active_storage_attachments, id: primary_key_type do |t|
      t.string     :name,     null: false
      t.references :record,   null: false, polymorphic: true, index: false, type: :string
      t.references :blob,     null: false, type: foreign_key_type

      if connection.supports_datetime_with_precision?
        t.datetime :created_at, precision: 6, null: false
      else
        t.datetime :created_at, null: false
      end

      t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true
      t.foreign_key :active_storage_blobs, column: :blob_id
    end
© www.soinside.com 2019 - 2024. All rights reserved.