如何对has_many_attached Active Storage关联进行联接?

时间:2019-06-28 18:38:34

标签: ruby-on-rails rails-activestorage

我想做一个数据库查询,查找所有附加了文件的记录。

class Departure 
  has_many_attached :pre_trip_documents
end

但这失败了:

Departure.joins(:pre_trip_documents).to_sql => #ActiveRecord::ConfigurationError (Can't join 'Departure' to association named 'pre_trip_documents'; perhaps you misspelled it?)

1 个答案:

答案 0 :(得分:0)

您可以这样做:

Departure.joins(:pre_trip_documents_attachments)

如果您查看has_many_attached的来源(可以找到here),这将更有意义。

总结一下,has_many_attached :pre_trip_documents的结果是:

has_many :"pre_trip_documents_attachments", -> { where(name: "pre_trip_documents") }, as: :record, class_name: "ActiveStorage::Attachment" ...

因此,致电Departure.joins(:pre_trip_documents_attachments)会给您:

SELECT "departures".* FROM "departures" INNER JOIN 
"active_storage_attachments" ON 
"active_storage_attachments"."record_id" = "departures"."id" AND 
"active_storage_attachments"."record_type" = 'Departure' AND 
"active_storage_attachments"."name" = 'pre_trip_documents'