Activerecord ActiveStorage blob文件名上的Rails作用域给出错误结果

Activerecord ActiveStorage blob文件名上的Rails作用域给出错误结果,activerecord,ruby-on-rails-5,rails-activestorage,Activerecord,Ruby On Rails 5,Rails Activestorage,我有以下使用ActiveStorage的型号: class ProofreadDocument < ApplicationRecord has_one_attached :file has_many :paragraphs, dependent: :destroy scope :with_file_named, -> (filename) { includes(:paragraphs).joins(file_attachment: :blob).whe

我有以下使用ActiveStorage的型号:

class ProofreadDocument < ApplicationRecord

  has_one_attached :file
  has_many   :paragraphs, dependent: :destroy

      scope :with_file_named, -> (filename) { 
includes(:paragraphs).joins(file_attachment: 
:blob).where("active_storage_blobs.filename = ?", filename).first}

如果给定文件名没有记录,如何修复此问题,使其返回0条记录?

您的作用域返回记录对象或
nil
。根据,范围应返回一个
ActiveRecord::Relation
;当它返回
nil
时,就像您的blob没有给定的文件名时一样,它相当于
all
(添加了强调):

添加用于检索和查询对象的类方法。该方法旨在返回ActiveRecord::Relation对象,该对象可与其他作用域组合如果返回
nil
false
,则返回
all
范围。

通过首先删除对
的调用来修改范围以返回关系:

scope :with_file_named, -> (filename) do
  includes(:paragraphs).joins(file_attachment: :blob).where("active_storage_blobs.filename = ?", filename)
end

当我用with with with ATTABLED_file替换联接(file_attachment::blob)时,我得到以下错误:ActiveRecord::StatementInvalid:PG::UndefinedTable:错误:当我执行以下操作时,表“active_storage_blob”的子句条目中缺少:校对文档。将_file_命名为(“BCI”)。首先。但是,当我使用连接(file_attachment::blob)时,它是有效的。很抱歉,是的,
带有_attached_file
并不等同于连接。我编辑了我的答案,删除了那条建议。
scope :with_file_named, -> (filename) do
  includes(:paragraphs).joins(file_attachment: :blob).where("active_storage_blobs.filename = ?", filename)
end