I have a webapp where I want to provide an advanced search in which the user enters an arbitrary amount of queries joined by AND's and/or OR's, like this:
(entered into the search box on the webpage)
name = "john" OR (occupation = "gardener" AND hobby.main = "reading")
In a prior post, I successfully implemented a system in which I directly convert queries formatted as above into valid SQL statements, and feed them straight into SQL to query the database.
This worked, but now I worry about three things:
- This wreaks of SQL injection
- If the user's input is invalid SQL throws an error which isn't very pretty...had some trouble handling these exceptions (though this part is doable).
- The code just seems really hacky and I wonder if there's a better way.
Well, I've heard there is a better way, by using search gems.
However, I've been having trouble finding gems that match my needs. Many of the gems seem too complex for what I need, and nothing that I've found made it clear exactly how you could implement specifically what I'm looking for -- where the user enters a dynamic number of queries joined by AND / OR statements.
Exactly how costly is it to just convert the statement straight to SQL syntax and inject it right in, like I'm doing right now? How easy is it to incorporate one of these gems for what I want? What would an "experienced" Rails developer do? I'm a complete noobie to Rails, so I don't have experience with any of this.
Aucun commentaire:
Enregistrer un commentaire