Over a million developers have joined DZone.

SQL-Injection Save Parser Generates ORDER BY Statement

·
Parses a string and generates an SQL order statement.

Because it's SQL-Injection save you can put it in your link_to method as :order => '+name' and then call #parse_order( params[:order] ).

Examples:
'+name' => 'name'
'+lastname+firstname' => 'lastname, firstname'
'+lastname-gender' => 'lastname, gender DESC'


module ActiveRecord
  class Base
    class << self

      def parse_order( order )
        order = order.to_s.gsub /([ \+\-][a-z_]+)/ do |match|
          next unless self.column_names.include?( match[1..-1] )

          case match[0, 1]
          when '-' then "#{ match[1..-1] } DESC, "
          else "#{ match[1..-1] }, "
          end
        end and order[0..-3]
      end
    
    end
  end
end
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}