2014-01-18 77 views
0

如何在Rails控制器中設置我的實例變量時將「OR」添加到此語句中?如何在設置Rails實例變量時將OR添加到where語句中?

@activities = PublicActivity::Activity.order("created_at DESC").where(owner_type: "User", owner_id: current_user.followed_users.map {|u| u.id}).where("owner_id IS NOT NULL").page(params[:page]).per_page(20)

我想@activities設定在owner_id等於或者current_user.id或current_user.followed_users記錄。我試着加入.where(owner_id: current_user.id),但似乎否定了整個查詢,我根本得不到結果。查詢這個樣子後,我加入到它:

@activities = PublicActivity::Activity.order("created_at DESC").where(owner_type: "User", owner_id: current_user.followed_users.map {|u| u.id}).where(owner_id: current_user.id).where("owner_id IS NOT NULL").page(params[:page]).per_page(20)

我如何添加OR條件讓我拉記錄,其中owner_id或者是CURRENT_USER或current_user.followed_users?

謝謝!

+0

你能解釋一下你的意思是「owner_id是...... current_user.followed_users」,因爲後者想必多元素關係還是數組?你的意思是「包含在」中嗎? –

+0

@PeterAlfvin,是的,這是一個數組,並將被翻譯成'IN' –

+0

@BillyChan其實,它可能是一個'ActiveRecord :: Associations :: CollectionProxy',對吧? :-) –

回答

1

快速修復是將current_user的id包含在數組中。

# Also use pluck instead of map 
ids = current_user.followed_users.pluck(:id) << current_user.id 
PublicActivity::Activity.order("created_at DESC") 
    .where(owner_type: "User", owner_id: ids).page(params[:page]) 
+0

感謝您的回答!工作很好。 – winston

1

Rails不支持「或」直接在此背景下,讓你無論是要重建你的查詢,以避免它(如圖the answer from Billy Chan)或提供SQL作爲參數傳遞給where如下所示:

.where("owner_type = 'User' and (owner_id = ? OR owner_id in (?))", current_user.id, 
    current_user.followed_users.pluck(:id)) 
+0

感謝您的回答!這也起作用了! – winston

0
@activities = PublicActivity::Activity.order("created_at DESC").where(owner_type: "User", owner_id: current_user.followed_users.map(&:id)+[current_user.id]).page(params[:page]).per_page(20) 

一號線的解決方案:)

相關問題