2017-12-20 4 views
0

私はRails 5アプリを構築しています。 このアプリで私は2つのモデル、ユーザーと目標を得た。ゴールのトップクリエイターを得る

ユーザーは多くの目標を持つことができます。

ほとんどの目標を作成した上位5人のユーザーを取得するためのクエリを作成します。

これは私がこれを試してみましたが、その後、私はユーザーだけではない、ほとんどの目標を持つもの取得目標のスキーム

create_table "goals", force: :cascade do |t| 
    t.integer "account_id" 
    t.integer "user_id" 
    t.integer "team_id" 
    t.integer "goal_id" 
    t.string "title" 
    t.text  "description" 
    t.string "gtype" 
    t.datetime "starts_at" 
    t.datetime "ends_at" 
    t.string "status",  default: "ontrack" 
    t.string "privacy" 
    t.integer "progress", default: 0 
    t.datetime "created_at",      null: false 
    t.datetime "updated_at",      null: false 
    t.string "ancestry" 
    t.index ["account_id"], name: "index_goals_on_account_id", using: :btree 
    t.index ["goal_id"], name: "index_goals_on_goal_id", using: :btree 
    t.index ["team_id"], name: "index_goals_on_team_id", using: :btree 
    t.index ["user_id"], name: "index_goals_on_user_id", using: :btree 
    end 

です。

Goal.distinct.order("user_id desc").limit(5) 

答えて

1

これはあなたにとって役に立ちます。

+0

ありがとうコントローラ内でこのメソッドを呼び出すことができます!それはうまく動作します。 –

1

次に、goles_countをcounter_cacheで並べ替えることをおすすめします。このhttp://railscasts.com/episodes/23-counter-cache-column

参照してくださいクエリは、

User.order("users.goles_count DESC").limit(5) 

がインデックスにgoals_count列を忘れてはいけないだろう。アウト 他の方法があることがあります。

User 
    .joins(:goals) 
    .select("users.*, count(goals.id) as gcount") 
    .group("users.id") 
    .order("gcount DESC") 
    .limit(5) 
0

あなたはスコープ方式

class User < ActiveRecord::Base 
    scope :top_user, -> (limit) { order("users.goles_count DESC").limit(limit) } 
end 

レールを試すことができますあなたは

@top_user = User.top_user(5) 
関連する問題