gpt4 book ai didi

ruby-on-rails-3 - 如何在rails中对表格列进行排序?

转载 作者:行者123 更新时间:2023-12-04 22:48:22 27 4
gpt4 key购买 nike

我按照 Ryan Bates 教程实现了这个 sort table columns它工作得很好,但是当我呈现索引页面时,表格已经按标题(asc)排序,我想只在用户单击列标题时对列进行排序。

我怎么能做到这一点?

代码

Controller

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);
}

最佳答案

你应该看看 Ransack。它在排序和复杂搜索方面做得很好。有一个很棒的RailsCasts视频应该可以帮助您并且侵入性小得多。

关于ruby-on-rails-3 - 如何在rails中对表格列进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14668553/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com