I assume you're permitting, for example, user-specified ordering? Unless you're permitting users to modify the DDL, I think your best bet is to interpret their request though some parameter and build the query rather than interpolate their input directly.
You might also look to see if the ActiveRecord adapter for the database you're using has an equivalent to PostgreSQL's quote_ident function. I don't know if the PostgreSQL adapter exposes that functionality directly though.
I have run in to this a few times as well. If you want to simply allow
them to sort on the columns in a table, ascending / descending, then
this code makes it safe:
sort_column = "default-column-name"
if allowed_columns.include?(params[:sortcolumn])
sort_column = params[:sortcolumn]
end
sort_direction = "asc"
if allowed_directions.include?(params[:sortdirection])
sort_direction = params[:sortcolumn]
end
and then use the sort column itself. This sanitizes user input by
following the rule of allowing specific actions and disallowing all
others.
Yeah, my initial concern was that there are a lot of sort / group
variations and they will change over time. I think what I'll end up
doing is writing a little helper object to offload that. So then I
have something like
Implementation will be simple - just check to see if the passed in
option is in a particular array, like you said. Then the finder
doesn't have to deal with that stuff, I express that this is a
potentially dangerous method, and it's obvious where changes to the
allowed options should go.