如何根据与另一个模型的关联从模型中获取ID列表

时间:2014-07-17 19:49:43

标签: ruby-on-rails

我的公司有很多客户。客户has_many消息。消息具有文本属性。

我正在尝试从其邮件的text属性中没有特定单词的客户那里获取customer_id列表。这是我到目前为止所做的:

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

当我这样做并得到该组中的客户数量时,它是正确的数字(大约7500),但当我去采取这样的ID时:

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...

3 个答案:

答案 0 :(得分:1)

尝试:

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

答案 1 :(得分: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 

答案 2 :(得分:0)

有相同的" id"查询中的字段(客户,消息),因此您需要添加一个id字段来对其进行排序。您可以添加重新订购(:id),以便按客户ID为您排序。

试试这个:

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