Skip to content

Instantly share code, notes, and snippets.

@jmcbri
Forked from TheKidCoder/example_controller.rb
Created March 8, 2017 10:55
Show Gist options
  • Save jmcbri/2c5b3b4579c830c4e56dfcc07e214a0c to your computer and use it in GitHub Desktop.
Save jmcbri/2c5b3b4579c830c4e56dfcc07e214a0c to your computer and use it in GitHub Desktop.
Rails - Sanitize Ordering Params
class ExampleController
include OrderingHelpers
def index
@clients = Clients.order(sanitized_ordering).where(user_id: current_user.id)
end
end
module OrderingHelpers
extend ActiveSupport::Concern
def sanitized_ordering
"#{sanitize_column(params[:order_by])} #{sanitize_column_direction(params[:sort_direction])}"
end
private
def sanitize_column(column)
resource.column_names.include?(column) ? column : "created_at"
end
def sanitize_column_direction(direction)
direction = direction.upcase
['DESC', 'ASC'].include?(direction) ? direction : "DESC"
end
def resource
controller_name.camelize.singularize.safe_constantize
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment