ruby-on-railssortingrailscasts

Railscast #228 Sortable Table Columns: doesn't change a direction


I followed Railscast's episode #228 to create a sortable table column in my app.

My issue: when I press on the column name first time - it shows orders in ascending order. Next time I click - it doesn't automatically show records in descending order; however, if I manually write desc: "http://localhost:3000/admin/users/2/records?direction=desc&sort=created_at" - it works perfectly; what's a problem?

My controller:

def records
    @records = @user.records.paginate(page: params[:page], per_page: 20).order(sort_column + " " + sort_direction)
  end

private
  def sort_column
    Record.column_names.include?(params[:sort]) ? params[:sort] : "created_at"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end

My application_helper:

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

My view:

<tr>
  <th><%= sortable "created_at" %></th>
</tr>

Solution

  • I had to write:

    direction = sort_column && sort_direction == "asc" ? "desc" : "asc"
    

    instead of:

    direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"