[英]How to query the inverse of a self-referential “has_many :through” relationship in Rails?
我們的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
類。 我的錯誤假設是,我可以直接在單個語句中描述連接並通過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.