2014-01-13 28 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]) }