【问题标题】:Rails scope on ActiveStorage blob filename gives erroneous resultsActiveStorage blob 文件名上的 Rails 范围会给出错误的结果
【发布时间】:2018-10-11 06:42:08
【问题描述】:

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

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

    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" = $1 AND 
"active_storage_attachments"."name" = $2 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 $3  [["record_type", 
"ProofreadDocument"], ["name", "file"], ["LIMIT", 1]]
(0.5ms)  SELECT COUNT(*) FROM "proofread_documents"

=> 576

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

【问题讨论】:

    标签: activerecord ruby-on-rails-5 rails-activestorage


    【解决方案1】:

    您的作用域返回一个记录对象或nil。根据the docs for the scope macro,范围应返回ActiveRecord::Relation;当它返回 nil 时,就像你在没有 blob 具有给定文件名时所做的那样,它等效于 all(添加了重点):

    添加用于检索和查询对象的类方法。该方法旨在返回一个 ActiveRecord::Relation 对象,该对象可与其他范围组合。 如果它返回nilfalse,则改为返回all 范围。

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

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

    【讨论】:

    • 当我用 with_attached_file 替换连接(file_attachment::blob)时,我收到以下错误:ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "active_storage_blobs" when我执行以下操作:ProofreadDocument.with_file_named("BCI").first。但是,当我使用 joins(file_attachment: :blob) 时,它可以工作。
    • 抱歉,是的,with_attached_file 不等于加入。我编辑了我的答案以删除那条建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 2019-04-06
    • 2021-05-12
    • 2014-05-19
    相关资源
    最近更新 更多