2016-06-10 40 views
0

我有一個連接表(收藏夾),它將用戶與menu_items(由餐具和餐館組成的另一個連接表)組合在一起。Ruby:如何總結/統計表項?

我想創建一個列出最受歡迎的菜餚(餐桌上最常出現的菜餚)和每個菜餚的頂級餐廳的桌子。我大部分都是在那裏,但不知道如何做點數。有小費嗎? Most Popular Dishes

這裏是我的代碼:

<div class="row"> 
<div class="col-md-12"> 
<table class="table table-striped table-hover"> 
    <tr> 
    <!-- <th>Dish comment</th> --> 
    <th>Dish</th> 
    <th>Restaurant</th> 
    <th>User</th> 
    <th>Actions</th> 
    </tr> 

    <% @favorites.each do |favorite| %> 
    <tr> 
    <!-- <td><%= favorite.dish_comment %></td> --> 
    <td><%= Dish.find(favorite.dishing_id).dish_name %></td> 
    <% d = Dishing.find(favorite.dishing_id) %> 
    <td><%= Restaurant.find(d.restaurant_id).name %></td> 
    <td><%= User.find(favorite.user_id).email %></td> 

回答

1

嘗試組,計數後加入。

User.joins(menu_items) 
      .select(count(menu_items.id) as dish_count, menu_items.dish_name, users.name) 
      .where(<conditions>) 
      .group(menu_items.dish_name) 
+0

謝謝!這在我的代碼中到底在哪裏?在這裏? <%@ favorites.each do | favorite | %> –

+0

請在您的控制器中嘗試 –