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
查询倒数,而不是一个实例方法。
这可能吗?
看看本教程是否能够提供一些你想要达到的内容的见解:https://www.railstutorial.org/book/following_users – eggroll