【发布时间】:2013-05-28 15:26:27
【问题描述】:
在 Rails 3.2 中说我有 3 个模型:Athlete、Event 和 Country
Class Athlete
has_many :events
has_many :countries, through: :event
end
Class Event
belongs_to :athlete, counter_cache: true
belongs_to :country, counter_cache: true
end
Class Country
has_many :events
has_many :Athletes, through: :event
end
所以我现在可以轻松地生成一个按照他们参加的赛事数量排序的运动员数组。
scope :ranked, :order => 'athletes.events_count DESC'
但是,如果我需要一组在特定国家/地区参加过比赛的运动员,并按照他们在该国家/地区的比赛次数排序。
#country
def show
@country.find(params[:id])
@athletes_leaderboard = Athlete.includes(:events).where(id: @country.events.uniq.map(&:athlete_id)).ranked
end
为我提供了在该国家/地区进行过比赛的运动员的唯一列表,但它是按他们的总事件数排名的,而不是按他们所在国家/地区的事件数。
如何在保持数据库性能的同时按国家/地区事件计数排序。
【问题讨论】:
标签: ruby-on-rails