Rails排序列表不使用模型列

时间:2013-03-18 20:47:53

标签: ruby-on-rails ruby-on-rails-3

我的观点中有以下表格:

  <table class="table table-bordered">
  <tr>
  <th><h3>Department</h3></th>
  <th><h3>Average Rating</h3></th>
  </tr>
  <tr>
  <%@unique_dept.each do |prod| %>
  <td><p class="text-center"><h4><%= prod.dept.capitalize %></h4></p></td>
  <td><p class="text-center"><h4><%= RatingSet.avg_rating_by_dept(prod.dept) %></h4></p></td>
  </tr>
  <%end%>
  </table>

我的控制器操作:

 def index
     @unique_dept = Product.find_by_sql("SELECT dept FROM products WHERE dept <> '' GROUP BY dept")
  end

我的模型方法:

 def self.avg_rating_by_dept(dept)
    RatingSet.joins(:products).where("dept = ?","#{dept}").average(:product_rating).to_f.round(2)
  end

如何对DepartmentAverage Rating进行排序,因为它们与模型中的列无关?

1 个答案:

答案 0 :(得分:0)

你可以做到

@unique_dept = Product.find_by_sql("SELECT dept FROM products WHERE dept <> '' GROUP BY dept") 
@unique_dept = @unique_dept.sort_by{ |prod| prod.dept }

评级为

RatingSet.joins(:products).where("dept = ?","#{dept}").average(:product_rating).to_f.round(2).order('products.product_rating')