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) andfollowed_id
, the user that is followed by the user withuser_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