[RUBY] [Rails] Display popular posts in ranking format [Easy]

I'm creating a personally developed app, and I think it will be easier to use if you can see it in the order of popular posts. Basically, I implemented it while referring to this article.

routes.rb

routes.rb


get 'rank' => 'shops#rank'

In my case I set it to the rank action of the shops controller.

shops_controller.rb

shops_controller.rb


 def rank
    @all_ranks = Shop.find(Favorite.group(:id).order('count(shop_id) desc').limit(5).pluck(:shop_id))
 end

Define rank method in shops controller. Display in the order of posts with the most likes.

rank.html.slim

ruby:rank.html.slim


- @all_ranks.each.with_index(1) do |shop, i|
  h5.col-md-5
    .card.shadow
      | No.
      = i
      | 
       = link_to shop.name, shop_path(shop)
       = link_to((image_tag shop.picture.url), shop_path(shop.id), class: 'shop-picture') if shop.picture.url.present?

Create a view file and display it. Excerpted as an example. After that, modify the appearance with CSS.

python


@all_ranks.each.with_index(1) do |shop, i|

From the above, you can display in descending order of likes.

Complete

The display in rank format has been completed easily.

Recommended Posts

[Rails] Display popular posts in ranking format [Easy]
[Japanese localization] i18n rails Easy Japanese localization view display only
Arrange posts in order of likes on Rails (ranking)
Display Flash messages in Rails
How to implement ranking functionality in Rails
[Rails] Show avatars in posts using Active Storage
[Ruby on Rails] Ranking display (total, average value)
Easy to display hello world with Rails + Docker
[Rails] Ranking and pagination in order of likes
[Rails 6] Ranking function
Group_by in Rails
[Rails] Return login result in JSON format (for beginners)
[Ruby on Rails] Posting score ranking function (whole display)
I summarized the display format of the JSON response of Rails
[Rails] How to display an image in the view