2016-06-07 80 views
0

在Rails中執行查詢以通過tag_id預先加載標籤來查找照片預加載照片上的標籤,但只有那些與查詢中的tag_id匹配的標籤......當照片稍後序列化。Rails ActiveRecord包含匹配查詢後的所有關聯

如何保留所有關聯的標籤,並返回具有這些特定標籤的照片?

使用此查詢:Photo.includes(:tags).where("tags.id IN (?)", [2, 5, 10).references(:tags)

我想有標籤2,5,和10中的所有照片,但如果照片具有標籤2和3,我希望它包括在其響應標籤3。

回答

0

可能有更好的方法來做到這一點,但我認爲這是有效的。

# Build a query for all photo IDs that have the specified tags. 
photo_ids_query = Photo.joins(:tags) 
         .where(:tags => { :id => [2, 5, 10] }) 
         .select("photos.id") 

# Load that list of photo IDs using a subquery. 
Photo.includes(:tags) 
    .where("photos.id IN (#{photo_ids_query.to_sql})")