2016-06-27 87 views
2

我有一個模型Notehas_and_belongs_to_many:Tags導軌模型具有所有關聯

我想查找所有至少同時具有ID 12的標籤的Notes。

目前,我有這樣的:

​​

這將返回有一個標籤使用任一ID 12所有Notes

我想返回任何包含兩個標籤的筆記。它可以不僅僅是這兩個標籤,但它至少必須同時具有這兩個標籤。

有什麼想法?我正在使用Rails 4.

回答

1

我從來沒有找到一個很好的解決方案。但是,如果您找不到合適的解決方案,我會分享我的解決方案。你可以像這樣做,

Note.includes(:tags).where(tags: { id: 1 }).references(:tags) && Note.includes(:tags).where(tags: { id: 2 }).references(:tags) 

令人驚訝它的成本只是一個SQL查詢和它的作品。您可以編寫一個方法,根據您的數組創建一個鏈,然後使用eval執行。

0

可以嘗試在您的調用中使用SQL語法嗎?

也許是這樣的:

Note.includes(:tags).where('EXISTS(SELECT 1 from tags where id = 1 and note_id = notes.id) and EXISTS(select 1 from tags where id = 2 and note_id = notes.id)').references(:tags).uniq 
0

你可以連續使用2個何在

.where(tags: { id: 1 }).where(tags: { id: 2 }) 
0

你可以鏈上的兩個地方的標籤很容易。

Note.includes(:tags).where(tags: { id: 1 }).where(tags: { id: 2 }).references(:tags)