title: How to sort table columns in rails?
body: <p>I implemented this following the Ryan Bates tutorial to <code>sort table columns</code> and it works great, however when I render the index page the table is already sorted by title (asc), and I would like to sort the columns only when the user click on the column header.</p>
  
  <p>How could I achieve this? </p>
  
  <p><strong>Code</strong></p>
  
  <p>controller</p>
  
  <pre><code>class ProductsController &lt; ApplicationController
    helper_method :sort_column, :sort_direction
  
    def index
      @products = Product.order(sort_column + " " + sort_direction)
    end
  
    # ...
  
    private
  
    def sort_column
      Product.column_names.include?(params[:sort]) ? params[:sort] : "name"
    end
  
    def sort_direction
      %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
    end
  end
  </code></pre>
  
  <p>helper_method</p>
  
  <pre><code>def sortable(column, title = nil)
    title ||= column.titleize
    css_class = column == sort_column ? "current #{sort_direction}" : nil
    direction = column == sort_column &amp;&amp; sort_direction == "asc" ? "desc" : "asc"
    link_to title, {:sort =&gt; column, :direction =&gt; direction}, {:class =&gt; css_class}
  end
  </code></pre>
  
  <p>index.html.erb</p>
  
  <pre><code>&lt;tr&gt;
    &lt;th&gt;&lt;%= sortable "name" %&gt;&lt;/th&gt;
    &lt;th&gt;&lt;%= sortable "price" %&gt;&lt;/th&gt;
    &lt;th&gt;&lt;%= sortable "released_at", "Released" %&gt;&lt;/th&gt;
  &lt;/tr&gt;
  </code></pre>
  
  <p><strong>CSS</strong></p>
  
  <pre><code>.pretty th .current {
    padding-right: 12px;
    background-repeat: no-repeat;
    background-position: right center;
  }
  
  .pretty th .asc {
    background-image: url(/images/up_arrow.gif);
  }
  
  .pretty th .desc {
    background-image: url(/images/down_arrow.gif);
  }
  </code></pre>