rails impressionist how to find 5 of most view item

991 Views Asked by At

I using this instance to find more view 5 Item, but cannot get the result.
Can teach me how to get it?

 @test = Item.limit(5).joins(:impressions).group("impressions.impressionable_id").order("count(impressions.impressionable_id) DESC")
3

There are 3 best solutions below

0
On BEST ANSWER

You can achieve the using counter cache. In this approach you've to create a new column to your model and add some configuration to your model. Thus, the gem will automatically update the view count.

Or, (not tested, but should work)

Item.joins(:impressions).group("impressions.impressionable_id").order("count(impression‌​s.id) DESC").first(5)
0
On

in your CreatePosts migration:

t.integer :visits, default: 0

in your post.rb:

is_impressionable counter_cache: true, column_name: :visits, :unique => :all

then:

Post.order(visits: :asc).limit(5)

And this thingy still works for rendering the count inside your post (Slim):

= post.impressionist_count

And yes, this works in PostreSQL and has no problem with activeadmin (quite handy for Dashboard) Hope it helps.

0
On

The answer given by Emu wouldn't work if you are using PostgreSQL. See here for explanation.

ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "items.id" must appear in the GROUP BY clause or be used in an aggregate function

Just add the primary key column of Item table and everything should work!

Item.joins(:impressions).
     group("items.id, impressions.impressionable_id").
     order("count(impression‌​s.id) DESC").
     first(5)