如何在最终模型上深入查询两个关系的模型以获取属性?

时间:2018-06-25 05:41:14

标签: ruby-on-rails activerecord

我想搜索包含Collections且标题与搜索查询匹配的所有Blob.item

一个Collection belongs_to Blobbelongs_to UserBlob belongs_to Itembelongs_to UserItem具有属性。

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}}?

2 个答案:

答案 0 :(得分:2)

假设aItem模型中的一个属性,那么查询将像这样:-

Collection.joins(blob: :item).where("items.a LIKE ?", "%{q}%");

答案 1 :(得分:1)

您可以将includesreferences一起使用,如下页所示:https://apidock.com/rails/ActiveRecord/QueryMethods/includes

Collection.
  includes(:blob).includes(:items).
  references(:items).references(:blob).
  where('items.a LIKE ?', "%{q}%")

仅使用includes会进行多个SQL查询,而仅使用references不会给您正确的集合信息。

您可能必须根据您的确切查询要求对此进行修改。