Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails find by part of string

I want to do a find in Rails basically to check if an object already exists in the database. I have a CSV, which I have little control over the format of it. I have a field in the CSV called 'name' which is the example I have contains 5 words. This field contains a name and address, but it is not confined to any format.

In my database I have fields such as 'name', 'address 1', 'address 2'. Basically I want to see if any part of the name field in the CSV matches up to any of the fields in my database.

I know I have to do a SQL like command probably but am not sure how to go about it.

like image 892
Sean Avatar asked Dec 04 '11 23:12

Sean


1 Answers

You can do it using LIKE :

User.where('name LIKE ?', "%#{@user.name}%")

The syntax for a LIKE sql statement to find a field for a given string fragment is to surround your string fragment with % characters, so the resulting SQL will look something like this

"SELECT \"users\".* FROM \"users\" WHERE (name LIKE '%Rob Phillips%')"
like image 195
iwasrobbed Avatar answered Oct 24 '22 22:10

iwasrobbed