Last week most viewed Items using Impressionist gem

怎甘沉沦 提交于 2019-12-23 23:13:47

问题


I have Post model and It's impressionable using Impressionist gem I want to show top 10 most visited Post in last month.

Here is the way I came up with:

Post.all.sort_by{|post| post.view_count_last_month}.first 10

and view_count_last_monthmethod is in Post model:

def view_count_last_week
    impressionist_count(:start_date => 1.week.ago)
end

But I think it's not good for performance because It loads all the Posts and then sort them by view_count_last_month method.

What is the best way to do that?

Thanks


回答1:


By looking at the Impressionist gem code for association and in impressionist_count, you can actually create your own scope like this:

  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) 
    }

now you can:

Post.order_by_starting_at(1.week.ago).limit(10)
Post.order_by_starting_at.limit(10)

EDIT:

However, it turned out that this worked even better -

Post.joins(:impressions).where("impressions.created_at<='#{Time.now}' and impressions.created_at >= '#{start_time}'").group("impressions.impressionable_id").order("count(impression‌​s.id) DESC")


来源:https://stackoverflow.com/questions/25565621/last-week-most-viewed-items-using-impressionist-gem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!