Mark
Mark

Reputation: 532

How to query the inverse of a self-referential "has_many :through" relationship in Rails?

Our Rails application uses a self-referential has_many relationship on our User class to track followings. This works to find followed_users:

class User < ApplicationRecord
  has_many :followings
  has_many :followed_users, through: :followings
end

class Following < ApplicationRecord
  belongs_to :user
  belongs_to :followed_user, class_name: 'User'
end

I was specifically asked to create a has_many :follower_users. I cannot seem to be able to generate the correct query to get the inverse. The closest I have come is an instance method which works

def followers
  User.includes(:followings).where followings: { followed_user_id: id }
end

but I was told to query the inverse through a has_many, not an instance method.

Is this possible?

Upvotes: 1

Views: 409

Answers (1)

Mark
Mark

Reputation: 532

I solved it after I read this post:

has_many :followers, foreign_key: :followed_user_id, class_name: 'Following'
has_many :follower_users, through: :followers, source: :user

I had a misunderstanding in how I first had to define the join relationship, then (in effect) follow that join through to the User class. It was my faulty assumption that I could directly describe the join and through in a single statement.

Upvotes: 2

Related Questions