Home>
I want to achieve

I want to display products in the order of product sales ranking.

trouble

Although product IDs can be obtained in the order of ranking, they will be in the order of ID when displayed.

Corresponding code
At the stage of populars, it is in the order of sales, but after that, it is just in the order of product id. .. ..
Controller.rb
def home
    populars = Order.group (: product_id) .order ('sum (quantity) desc'). pluck (: product_id)
    @populars = Product.where (id: populars)
 end
(Home.html.erb)
                            
                              <% @ populars.each do | popular |%>
                                
                                  <% = link_to product_path (popular.id) do%>
                                      <% product_images = Image.find_by (product_id: popular.id)%>
                                       <% = image_tag ("# {product_images.img1}")%>
                                        <% = popular.name%>
                                        
                                          <% product_tags = popular.tags%>
                                          <% product_tags.each do | product_tag |%>
                                                
                                                  <span><i></i></span><% = "# {product_tag.name}"%>
                                                
                                          <% end%>
                                        
                                         \<% = popular.price.to_s (: delimited)%>
                                  <% end%>
                                
                              <% end%>
                          
  • Answer # 1

    There are various ways to do this, so try searching for "rails where array order".

    array = [10,2,4,7,5]
    ordered_hoges = Hoge.find (array) .sort_by {| o | array.index (o.id)}

    https://qiita.com/shiraishiwataru/items/14b461ce813e2c0d6992