更好的方式是使用counter_cache
,因为您在查询中只使用一个表格,所以速度会更快。
这是您的歌曲类:
class Song < ActiveRecord::Base
has_many :listens
def self.top
order('listens_count DESC').limit(5)
end
end
然后,你的听力课:
class Listen < ActiveRecord::Base
belongs_to :song, counter_cache: true
end
请确保添加一个迁移:
add_column :comments, :likes_count, :integer, default: 0
加分项,添加测试:
describe '.top' do
it 'shows most listened songs first' do
song_one = create(:song)
song_three = create(:song, listens_count: 3)
song_two = create(:song, listens_count: 2)
popular_songs = Song.top
expect(popular_songs).to eq [song_three, song_two, song_one]
end
end
或者,如果你想使用上述方法,这里有一个更加简单的版本,使用一个类方法而不是
scope
。
def self.top
select('comments.*, COUNT(listens.id) AS listens_count').
joins(:listens).
group('comments.id').
order('listens_count DESC').
limit(5)
end
Song.where(:user_id => current_user.id).top.limit(5)
- clyfeWork.select('works.name, count(impressions.id) AS impressions_count').joins(:impressions).where('impressions.created_at >= ?', Time.now - 1.day).group('works.name').order('impressions_count DESC')
这个正确吗? - Daniel