Let me get started by saying I am a Rails newbie so I’m going to try and explain this the best that I can. As a reference, please see this thread which describes exactly what is happening to me, except the fix doesn’t seem to be working.
Problems with limit method in Rails 3.2 and hash ordering
I have a database with events that I am trying to sort by the primary key “id”. I tried following the Railscast on sortable table columns here:
http://railscasts.com/episodes/228-sortable-table-columns
The sorting works properly but the sort happens on the entire column instead of just the “last 50”.
Controller Code:
def index
@events = Event.order(sort_column + " " + sort_direction).page(params[:page]).last(50)
@events = @events.sort_by(&:id)
@events = Kaminari.paginate_array(@events).page(params[:page]).per(10)
end
def sort_column
Event.column_names.include?(params[:sort]) ? params[:sort] : "event_id"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "desc"
end
Application_helper:
def sortable(column, title = nil)
title ||= column.titleize
direction = column == sort_column && sort_direction == "desc" ? "asc" : "desc"
link_to title, :sort => sort_column, :direction => direction
end
Finally, in the index view, I call it like this:
<th><%= sortable "event_id" %></th>
I’m sorry if this question has already been answered, any help on this subject would be greatly appreciated.
EDIT
Thanks for the quick reply. I understand what you did there, but now I get an exception for some reason in my index view.
undefined method `id' for #<Array:0x00000004170c10>
Extracted source (around line #25):
22: <tbody>
23: <% @events.each do |event| %>
24: <tr>
25: <td><%= link_to event.id, event_path(event) %></td>
26: <td><%= event.event_date_time_local %></td>
27: <td><%= EventType.find(id = event.event_type_id).event_type %></td>
28: <td>
You said “instead of the last 50” but that is all you are returning. The last 50 found items after sorting based on sort_column and direction.
To get all events and then sort the last fifty you can do
Edit:
Sorry, instead of
try