我有 Post 模型,使用 Impressionist 可以印象深刻
gem
我想显示上个月访问量最高的 10 个帖子。
这是我想出的方法:
Post.all.sort_by{|post| post.view_count_last_month}.first 10
和view_count_last_month
方法位于Post
模型中:
def view_count_last_week
impressionist_count(:start_date => 1.week.ago)
end
但我认为这对性能不利,因为它会加载所有帖子,然后通过 view_count_last_month
方法对它们进行排序。
最好的方法是什么?
谢谢
最佳答案
通过查看Impressionist gem 代码为 association并在 impressionist_count ,您实际上可以像这样创建自己的范围:
scope :order_by_starting_at, -> (start_date){
impressions_table = Impression.quoted_table_name
query = if start_date.present?
"#{impressions_table}.created_at >= '#{start_date}' AND "
else
''
end
query += "#{impressions_table}.created_at <= '#{Time.now}'"
order(%Q{
COALESCE((
SELECT
COUNT(#{impressions_table}.impressionable_id)
FROM
#{impressions_table}
JOIN
#{Post.quoted_table_name} AS popular_posts
ON
popular_posts.id = #{impressions_table}.impressionable_id
AND
#{impressions_table}.impressionable_id = '#{self.to_s}'
WHERE
#{query}
), 0) DESC
})
}
scope :view_counts_for_first,-> (number){
order_by_starting_at.limit(number)
}
现在您可以:
Post.order_by_starting_at(1.week.ago).limit(10)
Post.order_by_starting_at.limit(10)
编辑:
然而,事实证明这效果更好 -
Post.joins(:impressions).where("impressions.created_at<='#{Time.now}' and impressions.created_at >= '#{start_time}'").group("impressions.impressionable_id").order("count(impressions.id) DESC")
关于ruby-on-rails - 上周浏览次数最多的使用印象派 gem 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25565621/