2016-11-22 85 views
4

我有兩個查詢,我需要它們之間的一個or,即我希望由第一個或第二個查詢返回的結果。傳遞給#or的關係必須在結構上兼容。不兼容的值:[:references]

第一個查詢是一個簡單的where(),它獲取所有可用的項目。

@items = @items.where(available: true) 

其次包括一個join()並給出當前用戶的項目。

@items = @items.joins(:orders).where(orders: { user_id: current_user.id}) 

我試圖以各種形式與Rails的or()方法結合起來,這些包括:

@items = @items.joins(:orders).where(orders: { user_id: current_user.id}) 
    .or(@items.joins(:orders).where(available: true)) 

,但我一直運行到這個錯誤,我不知道如何解決它。

Relation passed to #or must be structurally compatible. Incompatible values: [:references] 

回答

10

有一個known issue about it on Github

根據this comment你可能要重寫structurally_incompatible_values_for_or克服的問題:

def structurally_incompatible_values_for_or(other) 
    Relation::SINGLE_VALUE_METHODS.reject { |m| send("#{m}_value") == other.send("#{m}_value") } + 
    (Relation::MULTI_VALUE_METHODS - [:eager_load, :references, :extending]).reject { |m| send("#{m}_values") == other.send("#{m}_values") } + 
    (Relation::CLAUSE_METHODS - [:having, :where]).reject { |m| send("#{m}_clause") == other.send("#{m}_clause") } 
end 

而且總是有使用SQL的選項:

@items.joins(:orders).where("orders.user_id = ? OR items.available = true", current_user.id) 
+1

改爲使用SQL查詢。謝謝(你的)信息。 – frostbite

+0

@Andrey應該提到我的答案,而不是編輯你的並添加相同的。無論如何,+1爲第一個解決方案。 – RSB

+0

@RSB我打算從sql部分開始,比google搜索錯誤消息,並發現github問題。畢竟,我仍然決定添加我最初的想法,因爲它使代碼工作的代碼越少。 –

5

可以在此編寫查詢避免錯誤的老方法

@items = @items.joins(:orders).where("items.available = ? OR orders.user_id = ?", true, current_user.id) 

希望臨時噸幫助!

+0

這有效。謝謝。 – frostbite