簡體   English   中英

如何從控制器確定訂單

[英]How to determine the order from a controller

我的餐廳有很多員工,每個員工都有很多顧客評價。

我想創建一個統計頁面,該頁面顯示按每月平均評分排序的員工。

在員工模型中:

def avg_rating
   date = Date.today
   ratings_total = self.ratings.sum(:score, :conditions => {:created_at => (date.beginning_of_month..date.end_of_month)}).to_f
   ratings_count = self.ratings.count(:conditions => {:created_at => (date.beginning_of_month..date.end_of_month)}).to_f
   return (ratings_total/ ratings_count)
end

在餐廳管理員中,我有:

def restaurant_stats
  @restaurant = Restaurant.find(params[:restaurant_id])
  @employees = @restaurant.employees.all
end

在餐廳統計信息視圖中:

<table>
<% @employees.each do |employee| %>
 <tr>
  <td><%= employee.name %></td>
  <td><%= employee.avg_rating %></td>
 </tr>
<% end %>
</table>

我不確定如何正確安排員工? 我假設我必須在restaurant_stats操作中以正確的順序檢索值,而不僅僅是@ restaurant.employees.all,但由於雇員模型中使用的功能,我不確定如何操作

您可以從控制器執行以下操作:

@employees = @restaurant.employees.all.sort_by {|employee| employee.avg_rating}

或更簡潔

@employees = @restaurant.employees.all.sort_by(&:avg_rating)

請注意,這會將所有員工加載到內存中進行排序。

嘗試使用餐廳控制器:

@employees = @restaurant.employees.all.sort {|x,y| y.avg_rating <=> x.avg_rating }

要么

@employees = @restaurant.employees.all.sort_by(:avg_rating)

你可以創建一個數組並對其進行排序,我認為下面的作品,但尚未檢查

@employees = @restaurant.employees.collect {|p| [ p.name, p.avg_rating ]}
@employees.sort!{ |a,b| (a[1] <=> b[1]) }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM