商品の購入された回数に応じてランキングを表示する方法。
前提
・ECサイトの製作
・商品のテーブルをitemとしている
・注文された商品をOrderItemとしている
コントローラー
controller.rb
def index
@rank_items = OrderItem.find(OrderItem.group(:item_id).order('count(quantity) desc').limit(3).pluck(:id))
end
@rank_itemsの詳細説明.rb
OrderItem.group(:item_id) #OrderItemのitem_idが同じものをグループに分ける。
.order('count(quantity) desc') #ここでのorderは順に並べるという意味。descが大きい順にという意味。
.limit(3) #表示する最大数を3個に指定。
.pluck(:id)) #idを取り出す。
OrderItem.find() #pluckで取り出された数字をOrderItemのIDとする。
取り出した3つのidをviewで表示しましょう。
viewページ例
app/view/index.html.erb
<% @rank_items.each do |rank_item| %>
<%= attachment_image_tag rank_item.item, :image, size: '200x200',format: "jpeg",fallback: "cake.png",class:"img-responsive" %>
<p><%= rank_item.name %></p>
<p><%= rank_item.price %>円</p>
<% end %>
each文を使って3つの商品を表示させてます。