我有邮政模型,它是impressionable
using 印象派 https://github.com/charlotte-ruby/impressionist宝石
我想显示上个月访问量最高的 10 个帖子。
这是我想出的方法:
Post.all.sort_by{|post| post.view_count_last_month}.first 10
and view_count_last_month
方法在Post
model:
def view_count_last_week
impressionist_count(:start_date => 1.week.ago)
end
但我认为这对性能不利,因为它加载所有帖子,然后按view_count_last_month
method.
最好的方法是什么?
Thanks
通过查看印象派 https://github.com/charlotte-ruby/impressionist宝石代码为协会 https://github.com/charlotte-ruby/impressionist/blob/master/lib/impressionist/is_impressionable.rb#L15-L20 and in 印象派计数 https://github.com/charlotte-ruby/impressionist/blob/master/app/models/impressionist/impressionable.rb#L31-L49,您实际上可以像这样创建自己的范围:
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)
EDIT:
然而,事实证明,这样的效果更好——
Post.joins(:impressions).where("impressions.created_at<='#{Time.now}' and impressions.created_at >= '#{start_time}'").group("impressions.impressionable_id").order("count(impressions.id) DESC")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)