可能会重写计数的工作方式,或者找到更好的方法,来完成此操作



我在我的艺术家模型中有这个范围,它给了我艺术家,在一定时期内他们的受欢迎程度的顺序。popularity_caches表中的popularity每天计算一次

scope :by_popularity, lambda { |*args|
  options = (default_popularity_options).merge(args[0] || {})
  select("SUM(popularity) AS popularity, artists.*").
from("popularity_caches FORCE INDEX (popularity_cache_group), artists FORCE INDEX (index_artists_on_id_and_genre_id)").
where("popularity_caches.target_type = 'Artist'").
where("popularity_caches.target_id = artists.id").
where("popularity_caches.time_frame = ?", options[:time_frame]).
where("popularity_caches.started_on > ?", options[:started_on]).
where("popularity_caches.started_on < ?", options[:ended_on]).
group("artists.id").
order("popularity DESC")
}

这似乎工作,除了当我想得到计数:Artist.by_popularity.count。我得到一个时髦的哈希值作为回报(可能是在那段时间内拥有popularity_cache的艺术家的数量):

#<OrderedHash {295954=>1, 20143=>1, 157532=>1, 181291=>1, 300086=>1, 50100=>1, 262898=>1, 293888=>1, 130158=>2, 279943=>1, 336758=>1, 100201=>1, 134290=>2, 22726=>3, 144620=>2, 62497=>2 # snip

这可能是我想要的SQL:

SELECT COUNT(DISTINCT(artists.id)) AS count_all
FROM popularity_caches FORCE INDEX (popularity_cache_group), artists FORCE INDEX (index_artists_on_id_and_genre_id)
WHERE (popularity_caches.target_type = 'Artist')
  AND (popularity_caches.target_id = artists.id)
  AND (popularity_caches.time_frame = 'week')
  AND (popularity_caches.started_on > '2011-02-28 16:00:00')
  AND (popularity_caches.started_on < '2011-10-05')
ORDER BY popularity DESC

要获得计数,我必须创建一个单独的方法,它几乎做同样的事情,只是SQL的形式不同。它很糟糕,因为当我想要分页时,我必须传递两个东西:

@artists = Artists.by_popularity(some args).paginate(
  :total_entries => Artist.count_by_popularity(pass in the same args here as in Artist.by_popularity),
  :per_page => 5,
  page => ...
)

我闻起来很香,因为它很脆。

在ARel中有办法做到这一点吗?也许重写它如何计数的东西(distinct artists.id)和删除group by,所以它不返回一个哈希计数?

谢谢!

用惊人的船口解决。io:

PopularityCach.select(
  Arel::Nodes::Group.new(Artist.arel_table[:id]).count.as('count_all')
).where(
  PopularityCach.arel_table[:target_type].eq('Artist').and(
    PopularityCach.arel_table[:target_id].eq(Artist.arel_table[:id]).and(
      PopularityCach.arel_table[:time_frame].eq('week').and(
        PopularityCach.arel_table[:started_on].gt('2011-02-28 16:00:00').and(
          PopularityCach.arel_table[:started_on].lt('2011-10-05')
        )
      )
    )
  )
).order(:popularity).reverse_order

最新更新