2013-02-03 57 views
1

我在Ryan Bates教程之后实现了这个教程到sort table columns,它的效果很好,但是当我渲染索引页时,表已经按标题排序(asc),并且我只想在用户点击列标题。如何在rails中对表格列进行排序?

我怎么能做到这一点?

代码

控制器

class ProductsController < 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 

是helper_method

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 

index.html.erb

<tr> 
    <th><%= sortable "name" %></th> 
    <th><%= sortable "price" %></th> 
    <th><%= sortable "released_at", "Released" %></th> 
</tr> 

CSS

.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); 
} 
+0

的你所描述的排序最好在Javascript中实现,因为它从根本上说是一个客户端问题(而rails有助于解决服务器端问题)。 jquery的表格分类器插件正是你想要的:http://tablesorter.com/docs/。 – Reck

+1

嗨@Reck,谢谢你的推荐。作为一个学习过程,我想探索使用rails做这件事的可能性。 – evanx

+0

什么是您想要的产品列表上的默认排序? –

回答

5

你应该看看洗劫。它在分类和复杂搜索方面做得很好。有一个伟大的RailsCasts视频应该可以帮助你,而且侵入性要小得多。

+0

截至目前,ransack不能与边缘RoR一起使用。 https://github.com/activerecord-hackery/polyamorous/issues/6 –

+0

如果您遇到'polyamorous'问题,请尝试将其添加到您的宝石文件中。 'gem'polyamorous',github:'activerecord-hackery/polyamorous'' – kobaltz

+0

'gem'ransack',github:“activerecord-hackery/ransack”,分支:“rails-4.1”' 'gem'polyamorous',github: 'activerecord-hackery/polyamorous'' –

0

你可以试着放置如果支票上的索引方法

def index 
    if sort_column and sort_direction 
    @products = Product.order(sort_column + " " + sort_direction) 
    else 
    @products = Product.all() 
    end 
end 

def sort_column 
    Product.column_names.include?(params[:sort]) ? params[:sort] : nil 
end 

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