gpt4 book ai didi

ruby-on-rails - 通过某事拥有许多自身

转载 作者:行者123 更新时间:2023-12-02 21:51:51 24 4
gpt4 key购买 nike

所以,我有一个系统,用户可以关注作者(其他用户)。

用户模型:

  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

问题:我能够获取我正在关注的作者列表,但我也能够获取我的关注者列表。


已知: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

最佳答案

当然,我认为在发布问题后这是你的权利。但是,如果您认为有更优雅的方法,请发表评论:)

为了解决这个问题,我改变了:

用户模型:

  class User < ActiveRecord::Base
has_many :author_following, class_name: 'Following'
has_many :following, through: :author_following, source: :author
has_many :author_followers, foreign_key: 'author_id', class_name: 'Following'
has_many :followers, through: :author_followers, source: :user
end

以下模型:

  class Following < ActiveRecord::Base
belongs_to :user
belongs_to :author, class_name: "User"
end

关于ruby-on-rails - 通过某事拥有许多自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18473844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com