Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to find_by a field containing a certain string

I have a model named Topic, that has a name as a field.

So say I have a term I'm searching for, apple.

If I do a

Topic.find_by_name("apple")

I get a record back with the name apple. That's good -- but how do I change find_by_name so that it can find "apple juice" as well as "apple" -- basically, find names that contain the original query or exactly match the original query?

Edit: Thanks for all the response. I guess I should've been a little more clear earlier, but what if I want to find by a variable name (obviously I'm not going to want to find by the name "apple" everytime :) )?

How do I manipulate Topic.where to accommodate for this? So something like...

@topic = Topic.where(......., @name)
like image 551
varatis Avatar asked Mar 14 '12 19:03

varatis


2 Answers

I think something like this should work:

Topic.where("name like ?", "%apple%")

To accomodate for your edit:

Topic.where("name like ?", "%#{@search}%")

Basic string interpolation, you're using the value of @search inside the string %%, so you @search = "apple" then you end up with %apple%

like image 79
Deleteman Avatar answered Nov 04 '22 04:11

Deleteman


With PostgreSQL you can also use match operators:

Topic.where("name ~* ?", @search)
like image 14
Szymon Rut Avatar answered Nov 04 '22 04:11

Szymon Rut