简体   繁体   English

如何在Rails中查询自引用“ has_many:through”关系的逆函数?

[英]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. 我们的Rails应用程序在User类上使用自引用has_many关系来跟踪关注者。 This works to find followed_users : 这可以找到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 . 特别要求我创建一个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. 但是我被告知要通过has_many而不是实例方法来查询逆函数。

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. 我对如何首先定义联接关系有一个误解,然后(实际上)将联接遵循到User类。 It was my faulty assumption that I could directly describe the join and through in a single statement. 我的错误假设是,我可以直接在单个语句中描述连接并通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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