2014-01-13 26 views
0

我有一家擁有衆多員工的餐廳,每位員工都有很多客戶評級。如何確定控制器的訂單

我想創建一個統計頁面,顯示按其月度評級平均值排序的員工。

在員工型號:

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,但我不確定如何因爲在僱員模型中使用的功能

回答

1

您可以做,從控制器:

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

或更簡潔

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

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

0

在餐廳控制器:

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

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

,你可以創建一個數組和排序它 我覺得下面的作品,但沒有檢查它

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