0

How would I add "OR" to this where statement when setting my instance variable in a Rails controller?

@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)

I want to set @activities to records where owner_id is equal to either current_user.id or the current_user.followed_users. I tried adding .where(owner_id: current_user.id) but that seems to negate the entire query and I get no results at all. The query looked like this after I added to it:

@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)

How can I add an OR condition so that I pull records where owner_id is either current_user or current_user.followed_users?

Thanks!

5
  • Can you explain what you mean by "owner_id is ... current_user.followed_users", given that the latter is presumably a multi-element relation or array? Do you mean "is included in"? Commented Jan 18, 2014 at 18:36
  • @PeterAlfvin, yes that is an array and will be translated into IN
    – Billy Chan
    Commented Jan 18, 2014 at 18:50
  • @BillyChan Actually, it's probably an ActiveRecord::Associations::CollectionProxy, right? :-) Commented Jan 18, 2014 at 19:00
  • @PeterAlfvin, as map is method of Array, I think it will change this CollectionProxy and return Array.
    – Billy Chan
    Commented Jan 19, 2014 at 4:17
  • @BillyChan I agree that map will return an array, as implemented in Enumerable, but that doesn't mean that followed_users is an array. :-) Commented Jan 19, 2014 at 4:22

3 Answers 3

1

The quick fix is to include current_user's id in the array.

# 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
1

Rails doesn't support "OR" directly in this context, so you either have to reconstruct your query to avoid it (as shown in the answer from Billy Chan) or provide the SQL as an argument to the where as in:

.where("owner_type = 'User' and (owner_id = ? OR owner_id in (?))", current_user.id,
  current_user.followed_users.pluck(:id))
0
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)

One line solution :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.