我想做一个数据库查询,查找所有附加了文件的记录。
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?)
答案 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'