我们的 Rails 应用程序在我们的 User
类上使用自引用has_many
关系来跟踪关注。这可以找到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
我被特别要求创建一个has_many :follower_users
.我似乎无法生成正确的查询来获取相反的结果。我最接近的是一个有效的实例方法
def followers
User.includes(:followings).where followings: { followed_user_id: id }
end
但我被告知通过has_many
而不是实例方法查询反向。
这可能吗?
我在阅读这篇文章后解决了它:
has_many :followers, foreign_key: :followed_user_id, class_name: 'Following'
has_many :follower_users, through: :followers, source: :user
我有一个误解,即我首先必须定义连接关系,然后(实际上(遵循该连接到User
类。这是我错误的假设,我可以在单个语句中直接描述连接和通过。