查询嵌套计数
问题描述:
我有两个模型,一个User
和一个Exercise
,其中一个用户has_many :exercises
。 User
模型上有一个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+用户对象为所有的时间。我想限制到当前月份。
答
您不能在这里使用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
答
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
我不知道你想要什么,但是这将是很大的帮助希望享受:)
最后我用这个答案的精髓,创造了在运动模式通过限制一个范围月,然后通过这些计数创建一个用户数组,并从那里选择顶级用户 – Andy