我在活动页面上有一个"排序依据"下拉菜单,用户可以在其中查看许多事件,我想允许用户按名称(Alphebetical),日期(Created_At)以及可能(参加高/低的人数)对事件进行排序。
我怎样才能做到这一点?我猜测默认范围:例如,order,Event.where(:name,ASC),但我不确定,因为我以前从未这样做过。另外,我将如何在下拉列表中显示/使用范围?
我向您推荐了非常有用的宝石has_scope:https://github.com/plataformatec/has_scope
你可以用它做什么:
class Event < ActiveRecord::Base
scope ordered, lambda do |attribute, order|
return where("FALSE") unless self.attribute_names.include?(attribute.to_s)
order(attribute.to_sym, order.to_sym
end
class EventsController < ApplicationController
has_scope :ordered do |controller, scope, value|
scope.ordered(value, :desc)
end
# view
options = [['Name', 'name'], ['Date', 'date']]
select_tag("ordered", options_for_select(options, selected: params[:ordered]), onchange: "window.location.href = window.location.origin + window.location.pathname + '?ordered=' + $(this).val();"
我没有测试视图,您可能需要稍微更改代码。javascript 重定向不支持额外的 GET 参数!
看看 RailsCasts
http://railscasts.com/episodes/240-search-sort-paginate-with-ajax
这还包括pagination
和简单的搜索。但是,您可以从中获取所需的部分。
对于活动记录,您只需要将 .order(symbol) 附加到活动记录查询中。
对于字母,你可以做到。
Object.where(ARRGUMENT).order(:name)
或全部
Object.order(:name)
你不需要为此使用范围,对于这么简单的事情来说,它已经结束了。
如果你想创建一个交互式表,那么你可能需要考虑一个Javascript解决方案。这是对我来说效果最好的一个。
https://datatables.net/
我已经使用并且目前正在使用这种宝石,并取得了巨大的成功。
https://github.com/rweng/jquery-datatables-rails