2014-01-18 22 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) 

一号线的解决方案:)