Last active
August 29, 2015 14:11
-
-
Save DocX/9ca2209d88463aedb391 to your computer and use it in GitHub Desktop.
Rails powered API - resources ordering by URL params (ie /resources?order=created_at.desc)
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
# (c) 2014 Lukas Dolezal ([email protected]) | |
# MIT licence | |
# include in your base controller (ApplicationController): | |
# include OrderByParamsHelper | |
module OrderByParamsHelper | |
# use in controller: | |
# @resources = order_by_params(@resources, params[:order], :created_at) | |
# | |
# call your URL: | |
# /resources?order=created_at.desc | |
def order_by_params(resources, order_param, *allowed_fields) | |
return resources if order_param.nil? | |
order_fields = | |
order_param | |
.split(',') | |
.map{|o| o.split('.')} | |
.select{|o| | |
allowed_fields.include?(o[0].downcase.to_sym) && | |
[:desc, :asc].include?(o[1].downcase.to_sym) | |
} | |
.map{|o| "#{o[0].downcase} #{o[1].downcase}"} | |
if order_fields.empty? | |
resources | |
else | |
resources.order(order_fields.join(',')) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment