2017-09-27 206 views
0

我有兩個模型,一個User和一個Exercise,其中一個用戶has_many :exercisesUser模型上有一個cache_counter,exercise_count查詢嵌套計數

我想根據用戶在當月的運動計數製作排行榜。我想顯示具有該月份的最高鍛鍊次數以及計數的2個用戶。如果還有其他用戶與我想要顯示的第二位用戶具有相同的練習計數。 (顯示2+用戶)

當前查詢我有,

# User model 
scope :exercises_this_month, -> { includes(:exercises).references(:exercises) 
    .where("exercise_count > ? AND exercises.exercise_time > ? AND exercises.exercise_time < ?", 
    0 , Time.now.beginning_of_month, Time.now.end_of_month) 
} 

def User.leaders 
    limit = User.exercises_this_month.where("exercise_count > ?", 0).order(exercise_count: :desc).second.exercise_count 
    User.exercises_this_month.where("exercise_count > ? AND exercise_count >= ?", 0, limit) 
end 

將返回頂部2+用戶對象爲所有的時間。我想限制到當前月份。

回答

1

您不能在這裏使用counter_cache,因爲它始終存儲數字。另一個問題是,如果你有多個玩家擁有相同數量的練習,那麼你將錯過其次數最多的玩家。

# Exercise.rb 
scope :exercises_this_month, -> { 
    where("exercises.exercise_time > ? AND exercises.exercise_time <= ?", 
    Time.now.beginning_of_month, Time.now.end_of_month) 
} 

#User.rb 
players_this_month = User.joins(:exercises).group(:user_id).merge(Exercise.exercises_this_month).count ## 

sorted_counts = players_this_month.values.uniq.sort 

if sorted_counts.present? 
    second_place_counts = sorted_counts[-2] || sorted_counts[-1] #in case all have the same number 
    top_two_ids = players_this_month.map { |k,v| k if v >= second_place_counts } ##user ids with top two numbers 
end 
+0

最後我用這個答案的精髓,創造了在運動模式通過限制一個範圍月,然後通過這些計數創建一個用戶數組,並從那裏選擇頂級用戶 – Andy

0
gem 'groupdate' 
    model 
    def self.by_month(month_num) 
     self.where("cast(strftime('%m', created_at) as int) = # 
     {Date.today.strftime("%m")}") 
    end 
    controller 
     def report 
     @posts =Post.by_month(Date.today.strftime("%m")) 
     end 
    view 
    some think like this 
     = @posts.group_by_month(:created_at).count 

我不知道你想要什麼,但是這將是很大的幫助希望享受:)