我想搜索包含Collections
且标题与搜索查询匹配的所有Blob.item
。
一个Collection
belongs_to
Blob
和belongs_to
User
。 Blob
belongs_to
Item
和belongs_to
User
。 Item
具有属性。
Class Collection
belongs_to :blob
belongs_to :user
end
Class Blob
belongs_to :item
belongs_to :user
has_many :collections, foreign_key: :collection_id
end
Class Item
belongs_to :user
has_many :blobs, foreign_key : :item_id
validates :title, presence: true
end
我知道collection.rb
中的基本搜索应如下所示:
if search
where(["blob ILIKE ? OR user ILIKE ?", "%#{search}%", "%#{search}%"])
else
order('id DESC')
end
end
但这是行不通的,因为ILIKE会将搜索参数与blob_id
进行模式匹配。显然,我需要某种联接,但是我很难理解联接和包含的区别/用例。
如果我做Collections.joins(:blob)
,我会得到SELECT "collections".* FROM "collections" INNER JOIN "blobs" ON "blobs"."id" = "collections"."blob_id"
,这是朝着正确方向迈出的一步,但我无法查询Item
{{ 1}},因为has_many
上不存在Blobs
。
那么...我将如何编写查询来搜索属于包含特定属性的Item
的{{1}}的{{1}}?
答案 0 :(得分:2)
假设a
是Item
模型中的一个属性,那么查询将像这样:-
Collection.joins(blob: :item).where("items.a LIKE ?", "%{q}%");
答案 1 :(得分:1)
您可以将includes
与references
一起使用,如下页所示:https://apidock.com/rails/ActiveRecord/QueryMethods/includes
Collection.
includes(:blob).includes(:items).
references(:items).references(:blob).
where('items.a LIKE ?', "%{q}%")
仅使用includes
会进行多个SQL查询,而仅使用references
不会给您正确的集合信息。
您可能必须根据您的确切查询要求对此进行修改。