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
user.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
我想创建一个范围,通过followers.count订购用户
答案 0 :(得分:0)
使用以下查询,它为用户提供基于其关注者的升序。如果您希望asc
位于最高关注者的顶部,则可以将desc
替换为User
。
User.joins(:followers).group('users.id').order('count(*) asc')
更新:
如果要在用户模型中使用范围。
scope :by_followers_count, -> { joins(:followers).group('users.id').order('count(*) asc') }