Reputation: 527
I allow my user to enter a custom SQL query in an advanced form if he wants, and I feed his input straight into the "where" clause in my search method.
However, of course, sometimes the user will enter an invalid SQL query. Right now, this causes an error page to come up. I want it to instead display an "invalid syntax" statement.
def self.search(search)
if search
begin
includes(:hobbies, :games).where(search)
rescue SQL_syntax_error_exception # ?
#display error message
end
I'm puzzled by this because even when I tried the (supposedly) all-inclusive
rescue => e
it still didn't catch it...
Upvotes: 0
Views: 2247
Reputation: 5281
I would definitely not recommend doing this - you are going to have a tough time sanitizing the entire where clause with quotes intact.
As for catching the error,
begin
includes(:hobbies, :games).where(search)
rescue ActiveRecord::StatementInvalid => e
# do whatever
end
Note that there are bunches of exceptions that might occur here (not just ActiveRecord::StatementInvalid) so you might want to do something like:
...
rescue Exception => e
if e.class.ancestors.include? ActiveRecord::ActiveRecordError
# rescue stuff
else
# re-throw the exception
end
end
Upvotes: 1