adplus-dvertising

Active Records Query

Asked 3 months ago
Viewed 13 times

I will go stright to the point:

I have these two models:

  • User
  • Followed

The Followed model has

  • user_id (the user that follows another user) and
  • followed_id, the user that is followed by the user with user_id.

the User model looks like this:

has_many :followeds, foreign_key: :followed_id, dependent: :destroy

the Followed model looks like this

belongs_to :user

What I want to achieve is this: I want to retrieve the followers for the current_user (the logged in user).

I have some idea on what I should do, which is something like this:

1 - join users table with followeds table

2 - select users where users.id = followeds.user_id (the user who follows the current_user)

3 - and (condition) followeds.followed_id = current_user.id (the user who is followed is the current_user, the one logged in)

I don' t know if it can help, but the following query is the one that I succesfully used (with the kind help of stack overflow users) to retrive the users that a user follows:

@users = User.joins(:followeds).where(followeds: {user_id: current_user.id})

Based on that I believe that the query should look something like

@users = User.joins(:followeds).where(followeds: {followed_id: current_user.id})

and then some query to select users.id = followeds.user_id

asked 3 months ago

Correct Answer

If I clear understand your associations

User.where(id: Followed.select(:user_id).where(followed_id: current_user.id))

It will generate something like this SQL

SELECT * FROM users
WHERE id IN (
  SELECT user_id FROM followeds
  WHERE followed_id = <current_user_id>
);
answered 3 months ago