gpt4 book ai didi

ruby-on-rails - 通过某事有很多自己

转载 作者:行者123 更新时间:2023-12-02 04:53:09 26 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/

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