项目位于
http://code-dojo.herokuapp.com/
和
https://github.com/TylerSangster/Code-Dojo
我有一个包含以下模型的资源审查站点。
class Resource < ActiveRecord::Base
has_many :reviews
class Review < ActiveRecord::Base
belongs_to :resource
我添加了按名称、创建时间和成本排序的资源。我还想按评价最高的资源排序。
如何按 review.score 创建排序?
编辑资源控制器
def index
@resources = Resource.where(status: true).includes([:providers, :subjects, :formats, :reviews])
@resources = @resources.tagged_with(params[:tag]) if params[:tag]
@resources = @resources.order(sort_column + " " + sort_direction)
@resources = @resources.paginate(:page => params[:page], :per_page => 10)
respond_with @resources
end
私有方法
def sort_column
Resource.column_names.include?(params[:sort]) ? params[:sort] : "name"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
应用程序.rb
def sortable(column, title = nil)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, {:sort => column, :direction => direction}, {:class => css_class}
end
index.html.erb
<li><div class="btn btn-default"><%= sortable "created_at", "Most Recent" %></div></li>
<li><%= link_to "Highest Rated", resources_path, class:"btn btn-default" %></li>
<li><div class="btn btn-default"><%= sortable "cost" %></div></li>