2017-04-06 61 views
0

我在Rails中有一個查詢,它根據一系列OR語句獲取一組記錄。ActiveRecord按匹配條件數排序

@properties = policy_scope(Property).withdrawn_query(@hotlist_preference.withdrawn?) 
       .or(policy_scope(Property).fallen_through_query(@hotlist_preference.fallen_through?)) 
       .or(policy_scope(Property).time_on_market_query(@hotlist_preference.time_on_market?)) 
       .includes(:listings).paginate(page: params[:page], per_page: 20) 

基本上有3個查詢,一個簡單的版本可能是這樣的:

@properties = Property.where(state = withdrawn).or(where(state = fallen_through)).or(where(age = 4.weeks.ago)) 

我想要做的就是爲了這個查詢的次數或條件的每個結果滿足。所以說有一個財產與撤回狀態,其年齡是2個星期前,它將有一個訂單值爲2.如果可能我還想將訂單值添加到屬性的返回散列,所以我可以使用它在視圖中。

我一直在努力找到一個乾淨的方式來做到這一點,而不再通過一組相同的查詢運行結果。

+0

您正在使用什麼數據庫? –

+0

我不知道這是否被ActiveRecord支持,但是你可以考慮下降到[原始SQL](http://stackoverflow.com/a/3289152/1954610)來實現這個目標? –

+0

我使用的是PostgreSQL – rmaspero

回答

0

這看起來非常髒,但只有這樣才能達到這個

@properties = Property.where(state = withdrawn).or(where(state = fallen_through)).or(where(age = 4.weeks.ago)).order('case when properties.state = 'withdrawn' && properties.state = 'fallen_through' && properties.age = 'your date' then 10 when hen properties.state = 'withdrawn' && properties.state = 'fallen_through' then 9 when properties.state = 'fallen_through' && properties.age = 'your date' then 9 when properties.state = 'withdrawn' && properties.age = 'your date' then 9 when properties.state = 'withdrawn' && properties.state = 'fallen_through' && properties.age = 'your date' then 10 when properties.state = 'withdrawn' then 8 when properties.state = 'fallen_through' then 8 when properties.age = 'your date' then 8 else 0 end) 
+0

我把你的訂單聲明進一步整理了一下。因爲我認爲我可以這樣做:(case when condition1 THEN 1 ELSE 0 END + CASE WHEN condition2 THEN 1 ELSE 0 END + CASE WHEN condition3 THEN 1 ELSE 0 END) – rmaspero

+0

是的,這是更清潔。 – user3775217