Rails ActiveStorage blob 文件名范围给出错误结果

Rails scope on ActiveStorage blob filename gives erroneous results

我有以下使用 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}

当有匹配文件名的记录时,它工作得很好。但是,当我搜索文件名不存在的记录时,它 returns 所有记录。

    pry(main)> ProofreadDocument.with_file_named("M6").count
      ProofreadDocument Load (6.9ms)  SELECT  "proofread_documents".* FROM 
"proofread_documents" INNER JOIN "active_storage_attachments" ON 
"active_storage_attachments"."record_id" = "proofread_documents"."id" AND 
"active_storage_attachments"."record_type" =  AND 
"active_storage_attachments"."name" =  INNER JOIN "active_storage_blobs" 
ON "active_storage_blobs"."id" = "active_storage_attachments"."blob_id" 
WHERE (active_storage_blobs.filename = 'M6') ORDER BY 
"proofread_documents"."id" ASC LIMIT   [["record_type", 
"ProofreadDocument"], ["name", "file"], ["LIMIT", 1]]
(0.5ms)  SELECT COUNT(*) FROM "proofread_documents"

=> 576

如果没有给定文件名的记录,我该如何解决这个问题,以便 returns 0 条记录?

您的范围 return 是一个记录对象或 nil。根据 the docs for the scope macro,范围应该 return 和 ActiveRecord::Relation;当它 returns nil 时,就像你在没有 blob 具有给定文件名时所做的那样,它等同于 all(添加了强调):

Adds a class method for retrieving and querying objects. The method is intended to return an ActiveRecord::Relation object, which is composable with other scopes. If it returns nil or false, an all scope is returned instead.

通过删除对 first:

的调用,将范围修改为 return 关系
scope :with_file_named, -> (filename) do
  includes(:paragraphs).joins(file_attachment: :blob).where("active_storage_blobs.filename = ?", filename)
end