2014-10-06 28 views
0

在Rails應用程序中,我需要返回包含多列的ActiveRecord集合,但只有1列必須是唯一的。有一個默認範圍不是唯一值。如何從單列中選擇唯一值,並使用默認範圍,返回多列

默認適用範圍

default_scope { order('executed_at DESC') } 

當前的查詢,而獨特:條款。

Search.where(organization_id: @my_array_of_ids) 
     .executed_after(from_date_time) 
     .limit(100) 
     .pluck(:terms) 

executed_after(from_date_time)是一個範圍爲好。如何更改上述查詢以返回獨特的術語而不使用.uniq方法?我希望這是一個單一的SQL語句。

+0

這對您有幫助嗎? http://stackoverflow.com/questions/16913969/postgres-distinct-but-only-for-one-column – 2014-10-06 16:03:46

回答

0

我也發現了這一點:

Convert SQL query to Active Record query in Rails 4

通知的Model.distinct(:列)

編輯:

我猜它是這樣的,但我d需要更多信息:

Search.distinct(:terms).select(:executed_at) 
.where(organization_id: @my_array_of_ids) 
    .executed_after(from_date_time) 
    .limit(100) 
    .group(:executed_at) 
+0

這給了我錯誤'PG :: GroupingError:錯誤:列「searches.executed_at」必須出現在GROUP BY子句中或用於聚合函數中'我認爲它與默認範圍有關 – cheeseandpepper 2014-10-06 16:14:19

+0

這是一個SQL錯誤,您需要使用'.group(:executed_at)將該列添加到group by子句中)' – 2014-10-06 16:16:14

+0

我試過了,問題在於execution_at是帶有所有獨特結果的時間戳。我不在乎這些是否獨一無二;只有條件是唯一的。 – cheeseandpepper 2014-10-06 16:31:17

相關問題