2014-02-21 18 views
1

我在事件頁面上有一個'排序依據'下拉菜單,用戶可以查看一些事件,我想允許用戶按名稱(Alphebical),日期(Created_At)和可能(Number of參加hi/low的人)。如何添加按選項排序?

我該如何做到這一點?我猜測與默認範圍:命令,Event.where(:名稱,ASC)例如,但我不知道,因爲我從來沒有這樣做過..此外,我將如何顯示/使用範圍在下拉?

回答

2

我推薦你極有用的寶石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參數!

+0

真棒!你介意分享我如何在視圖中實現這一點嗎?非常感謝! –

+0

我添加了一個示例@SonnyBlack – MrYoshiji

0

對於活動記錄,您只需將.order(符號)添加到活動記錄查詢。

你可以做字母。

Object.where(ARRGUMENT).order(:name) 

或所有

Object.order(:name) 

您不需要使用範圍本是過來殺掉的東西這麼簡單。

如果你想創建一個交互式表格,那麼你可能要考慮一個Javascript解決方案。這是對我來說最合適的一個。

https://datatables.net/

我已經使用,目前使用這種寶石大獲成功。

https://github.com/rweng/jquery-datatables-rails

相關問題