简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM