-
-
Save kivanio/c73b8f7497416c814feb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/item.rb | |
require 'concerns/sortable' | |
class Item < ActiveRecord::Base | |
include Sortable | |
attr_accessible :title | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/controllers/items_controller.rb | |
class ItemsController < ApplicationController | |
def index | |
@items = Item.sorted(params[:sort], params[:direction]) | |
respond_to do |format| | |
format.html | |
format.json { render json: @items } | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/concerns/sortable.rb | |
require 'active_support/concern' | |
module Sortable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def sorted(column, direction = nil) | |
column = map_column(column) | |
# Create a string to sort with (e.g. "title ASC") | |
sort_string = [column, direction].reject(&:blank?).join(' ') | |
order(sort_string) | |
end | |
private | |
def map_column(column) | |
mapping = { | |
# param => table column | |
'name' => 'title' | |
# etc... | |
} | |
column = mapping[column] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment