我正在进行排序功能,以便对用户列表进行排序。此排序功能旨在根据属性(列)进行排序。用户模型有一个group_id列,但我不想按编号排序,我想按公司名称排序。顺便说一句,
公司:has_many用户
和
用户:belongs_to公司
这是我的index.html.erb:
<table class="pretty" border="1" cellpadding="10">
<tr>
<th></th>
<th><%= sortable "name" %></th>
<th><%= sortable "email" %></th>
<th><%= sortable "company_id" %></th>
<th>DELETE</th>
</tr>
<% for user in @users %>
<tr class="<%= cycle('oddrow', 'evenrow') -%>">
<td><%= gravatar_for user %></td>
<td><%= link_to user.name, user %></td>
<td><%= user.email %></td>
<td><%= user.company.name unless user.company_id.blank? %></td>
<td><% if current_user.admin? || ( ( current_user.developer? && !current_user?(user) ) && (user.boss_id == current_user.id) ) %>
|| <%= link_to "delete", user, method: :delete,
data: { confirm: "You sure?" } %>
<% end %></td>
</tr>
<% end %>
</table>
<%= will_paginate @users %>
这是来自application_helper.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, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class}
end
这是users_controller.rb:
helper_method :sort_column, :sort_direction
def index
@users = User.where(:developer => false, :admin => false).search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 10, :page => params[:page])
end
private
def sort_column
User.column_names.include?(params[:sort]) ? params[:sort] : "name"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
那么,如何修改它以便按Company.name而不是User.company_id进行排序?
答案 0 :(得分:0)
我通过将<%= sortable "company_id" %>
更改为<%= sortable("name", "Company") %>
并更改
User.column_names.include?(params [:sort])? params [:sort]:“name”
到
((User.column_names.include?(params [:sort]))||(Company.column_names.include?(params [:sort])))? params [:sort]:“name”