Reputation: 145
I have an application with 4 models, Clients, Projects, Sprints and tasks. Im showing the task index with all the taks in the db, im trying to set sortable columns, and i actually made it, here is the code, im using metasearch gem.
<%- model_class = Task.new.class -%>
<h1><%=t '.title', :default => model_class.model_name.human.pluralize %></h1>
<table class="table">
<thead>
<tr>
<th><%= sort_link @search, :id %></th>
<th><%= sort_link @search, :client_id%></th>
<th><%= sort_link @search, :name %></th>
<th><%= sort_link @search, :description %></th>
<th><%= sort_link @search, :status %></th>
<th><%= sort_link @search, :created_at %></th>
</tr>
</thead>
<tbody>
<% @tasks.each do |task| %>
<tr onclick="location.href='<%= sprint_task_path(task.sprint_id,task) %>'">
<td><%= task.id %></td>
<td><%= task.sprint.project.client.name %></td>
<td><%= link_to task.name, sprint_task_path(task.sprint_id,task) %></td>
<td><%= task.description %></td>
<% if task.status == nil %>
<td> Incompleta</td>
<%else%>
<td> Completa</td>
<%end%>
<td><%= task.created_at %></td>
</tr>
<% end %>
</tbody>
This is working, however in the second column which is the client_id is not, and i want to sort it through the clients name. Thanks in advanced.
Upvotes: 1
Views: 333
Reputation: 35533
As per the documentation here, you should create 2 new scopes that handle the sorting logic:
scope :sort_by_client_name_asc, joins(:client).order('clients.name ASC')
scope :sort_by_client_name_desc, joins(:client).order('clients.name DESC')
Then you can use this sort link code:
<th><%= sort_link @search, :client_name %></th>
If you have already defined the joins elsewhere and are including them in the scope that created the search, you can likely skip the custom sort scopes and just use the link as shown above.
Upvotes: 2