1

I have a feeling this question is easy, but maybe I am just overthinking it..

I have an Active Record query that looks like this:

@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: current_user.followed_users, owner_type: "User", kind: "Activity")

This works great, but I'd like to add current_user as a possible :owner. So I've tried many options, including:

@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: [[current_user.followed_users], [current_user]], owner_type: "User", kind: "Activity")
@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: [current_user.followed_users, current_user], owner_type: "User", kind: "Activity")

However I'm getting errors like:

Cannot visit User::ActiveRecord_Associations_CollectionProxy

Can anyone spot the mistake I'm making...thanks

Justin
  • 4,922
  • 2
  • 27
  • 69

2 Answers2

2

current_user.followed_users is an ActiveRecord_Associations_CollectionProxy, but you only want the ids, like so - current_user.followed_users.collect(&:id)

Using your example, the full query would look something like this:

@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: [[current_user.followed_users.collect(&:id)], [current_user.id]], owner_type: "User", kind: "Activity")

Brad Werth
  • 17,411
  • 10
  • 63
  • 88
  • 2
    use #pluck instead of collect to only grab the ids http://stackoverflow.com/questions/12176102/what-is-the-difference-between-pluck-and-collect-in-rails – Steven Ferguson Jun 18 '14 at 00:19
2

You can append the current_user to the array of followed_users. Try this:

allowed_users = current_user.followed_users << current_user
@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: allowed_users, owner_type: "User", kind: "Activity")

Or you can just add current_user as a one element array to the their followed_users.

allowed_users = current_user.followed_users + [current_user]
@activities = PublicActivity::Activity.includes(:owner, :trackable).where(owner_id: allowed_users, owner_type: "User", kind: "Activity")
Joe Kennedy
  • 9,365
  • 7
  • 41
  • 55
  • thanks this does work as well. If brad doesn't edit his current answer, then I will accept this. – Justin Jun 17 '14 at 23:10