0

I'm using Public Activity to create a feed, and I'd like to filter the activities. I don't want to show to the current_user its own activities so I have:

@activities = PublicActivity::Activity.where.not(owner_id: current_user.id)

And this works well. I want to add a second filter, which is to only display activities that belong to the users followed by current_user.

I can get all the followed users using:

@users = current_user.following

My question is: how can I filter the activities by checking if owner_id is the id of a user included in @users ?

EDIT:

activities table:

create_table "activities", force: :cascade do |t|
    t.integer  "trackable_id"
    t.string   "trackable_type"
    t.integer  "owner_id"
    t.string   "owner_type"
    t.string   "key"
    t.text     "parameters"
    t.integer  "recipient_id"
    t.string   "recipient_type"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "read",           default: false
    t.string   "origin"
  end

1 Answer 1

1

Try the following:

Activity.joins(:owner).where.not(
           users: {id: current_user.id}
       ).joins(owner: :followings).where(
           followings: { follower_id: current_user.id }
       )

This translates to all activities DO NOT belonging to the current_user but DO belong to a user followed by current_user.

You may need to replace values were appropriate.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your answer. Howerver, I get this error: Association named 'users' was not found on PublicActivity::Activity This might be due to the fact that by default, the activities table as a owner_id attribute but not a user. Should I add a reference to the user table in the activity table ? I've edited my question with the table
No need to change the reference when a simple change to query will do: Activity.joins(:owners). See my update
Same error: Association named 'owners' was not found on PublicActivity::Activity
Then do :owner instead of owners
Whatever the relation is named goes in the joins
|

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.