I’m implementing a simple search function that should check for a string in either the username, last_name and first_name. I’ve seen this ActiveRecord method on an old RailsCast:
http://railscasts.com/episodes/37-simple-search-form
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
But how do I make it so that it searches for the keyword in name, last_name and first name and returns the record if the one of the fields matched the term?
I’m also wondering if the code on the RailsCast is prone to SQL injections?
Thanks a lot!
I assumed your model name is Model – just replace it with your real model name when you do the actual query:
About your worries about SQL injections – both of code snippets are immune to SQL injections. As long as you do not directly embed strings into your WHERE clause you are fine. An example for injection-prone code would be: