2016-09-05 3 views
1

Herokuのコンソールレール範囲(ソーススルーにhas_many)

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

(1.4ms)SELECT COUNT(*)INNERが "ユーザ" ON "関係" JOIN "ユーザ" FROM。「ID "= "関係"。" follower_id」 "関係"。 "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

使用して、ユーザーを注文しますスコープを作成したい、それが上の昇順であなたのユーザーを提供します彼らの追随者の基礎。 Userが一番上にあり、最大フォロワーが必要な場合は、ascdescに置き換えることができます。

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

更新:

あなたはUserモデルに適用範囲を使用したい場合。

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

しかし、これからどのようにscopeを作成してuser.rbに入れるのですか?私の理解はコントローラの中にこのようなものを置くことを避けるのが最善であり、それがモデルに入るべきだということです。 –

+0

心配しないで、私はcounter_cacheを作成しました。 –

+0

@TimmyVonHeiss私は自分の答えを更新し、ユーザーモデルのスコープに移動しました。 – Aamir