2014-07-17 82 views
2

我有很多客戶的公司。客戶has_many消息。消息具有文本屬性。如何從一個模型中獲取一個基於關聯到另一個模型的ID列表

我試圖從沒有在消息的文本屬性中包含特定單詞的客戶獲取customer_ids的列表。這是我到目前爲止有:

company.customers.includes(:messages).references(:messages).where('messages.text NOT LIKE ?', "% summer %") 

,當我做到這一點,得到該組中的客戶的數量,這是正確的號碼(7500),但是當我去掐了IDS像這樣:

company.customers.includes(:messages).references(:messages).where('messages.text NOT LIKE ?', "% summer %").pluck(:id).count 

返回80000分一樣的結果,這是不正確

我到底做錯了什麼?

編輯:

PG::AmbiguousColumn: ERROR: column reference "id" is ambiguous 
LINE 1: SELECT id FROM "customers" LEFT OUTER JOIN "messages" ON "me... 
      ^
: SELECT id FROM "customers" LEFT OUTER JOIN "messages" ON "messages"."customer_id" = "customers"."id" WHERE "customers"."company_id" = $1 AND (messages.text NOT LIKE '% summer %') 
PG::AmbiguousColumn: ERROR: column reference "id" is ambiguous 
LINE 1: SELECT id FROM "customers" LEFT OUTER JOIN "messages" ON "me... 
      ^
: SELECT id FROM "customers" LEFT OUTER JOIN "messages" ON "messages"."customer_id" = "customers"."id" WHERE "customers"."company_id" = $1 AND (messages.text NOT LIKE '% summer %') 
ActiveRecord::StatementInvalid: PG::AmbiguousColumn: ERROR: column reference "id" is ambiguous 
LINE 1: SELECT id FROM "customers" LEFT OUTER JOIN "messages" ON "me... 
+0

如果刪除了'.references什麼:從查詢'(消息)? ('.joins'觸發一個'INNER JOIN'來創建重複項,'.includes'觸發'LEFT OUTER JOIN'不會創建重複項) – MrYoshiji

+0

但我沒有使用.joins ...我會在哪裏放置? –

+0

只需嘗試'company.customers.includes(:messages).where('messages.text NOT LIKE?',「%summer%」)。count'來查看它是否有效。如果是這樣,我會發布解決問題的答案,這裏 – MrYoshiji

回答

0

剛剛鏈ids到您的查詢的末尾:從試圖回答錯誤

company.customers.includes(:messages).references(:messages).where('messages.text NOT LIKE ?', "% summer %").ids 

你也應該能夠去除引用:

company.customers.includes(:messages).where('messages.text NOT LIKE ?', "% summer %").ids 
+0

不起作用。 (編輯中顯示) –

+0

還應該提及它應該是「company.customers」而不是「company.customer」...這是我的錯誤..修正了編輯 –

+0

我不斷收到模棱兩可的錯誤 –

1

試穿:

company.customers.includes(:messages).references(:messages).where('messages.text NOT LIKE ?', "% summer %").distinct.pluck(:id).count 
0

查詢(客戶,消息)中有相同的「id」字段,因此您需要添加一個id字段來對其進行排序。您可以添加重新排序(:id),以便按客戶ID排序。

試試這個:

相關問題