2017-02-11 19 views
1

我們的Rails應用程序在我們的User類中使用自我指涉has_many關係來跟蹤以下內容。這可用來尋找followed_users如何在Rails中查詢自引用「has_many:through」關係的逆函數?

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查詢倒數,而不是一個實例方法。

這可能嗎?

+1

看看本教程是否能夠提供一些你想要達到的內容的見解:https://www.railstutorial.org/book/following_users – eggroll

回答

2

我解決了這個問題後,我讀this帖子:

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

我曾在我第一次不得不來定義連接關係,那麼(實際上)一個誤區遵循通過加入到User類。這是我錯誤的假設,我可以直接在一個聲明中直接描述連接。

相關問題