0

我认为有下表:

  <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因为它们与我的模型中的列没有关联?

4

1 回答 1

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')
于 2013-03-18T21:04:01.977 回答