gpt4 book ai didi

ruby-on-rails - follower_id 的 rails 作用域(has_many through source)

转载 作者:行者123 更新时间:2023-11-29 13:51:59 25 4
gpt4 key购买 nike

Heroku 控制台

u = User.find(1)
u.followers.count

(1.4ms) SELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" = $1 [["followed_id", 1]]

=> 1

relationship.rb

class Relationship < ActiveRecord::Base
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
end

用户.rb

has_many :active_relationships, class_name:  "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower

我想创建一个范围,按用户的关注者数量对用户进行排序

最佳答案

使用以下查询,它会根据关注者的升序为您提供用户。如果您希望 User 位于顶部且关注者最多,则可以将 asc 替换为 desc

User.joins(:followers).group('users.id').order('count(*) asc')

更新:

如果你想在 User 模型中使用 Scope。

scope :by_followers_count, -> { joins(:followers).group('users.id').order('count(*) asc') }

关于ruby-on-rails - follower_id 的 rails 作用域(has_many through source),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39323140/

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