所以,我有一个系统,用户可以关注作者(其他用户)。
用户模型:
class User < ActiveRecord::Base
has_many :author_following, class_name: 'Following'
has_many :following, through: :author_following, source: :author
has_many :followers, foreign_key: 'author_id', through: :author_following, source: :user
end
以下型号:
class Following < ActiveRecord::Base
belongs_to :user
belongs_to :author, foreign_key: 'author_id', class_name: "User"
end
问题:我能够获得我正在关注的作者列表,但我能够获得我的关注者列表。
Given:u
是一个有效的用户,正在关注其他人并拥有关注者
u.following
生成以下 SQL:
SELECT "users".* FROM "users" INNER JOIN "followings" ON "users"."id" = "followings"."author_id" WHERE "followings"."user_id" = $1 [["user_id", 1]]
哪个是对的..
u.followers
生成以下 SQL:
SELECT "users".* FROM "users" INNER JOIN "followings" ON "users"."id" = "followings"."user_id" WHERE "followings"."user_id" = $1 [["user_id", 1]]
哪个是错的。。
理想情况下,此 SQL 将是WHERE "followings"."author_id" = $1