jpn
jpn

Reputation: 273

Searching for a string within a string in an attribute of an instance of a class

I can't seam to get this db query in my rails app. Here's my code from my controller:

User.where(:sport => "/\bFootball").all

That created this query/response:

SELECT "users".* FROM "users"  WHERE "users"."sport" = 'Football'
=> []

==========================================

But this:

User.where(:sport => "Football").all

Returns this:

SELECT "users".* FROM "users"  WHERE "users"."sport" = 'Football'
=>[ARRAY OF DESIRED USERS]

Not sure of the syntax here

Upvotes: 0

Views: 50

Answers (2)

Sahil
Sahil

Reputation: 504

You can also use a regular expression to make this query. The syntax for the same is:

User.where(sport: /Football/).to_a

Incase you want the term 'Football' to be case insensitive, you can use:

User.where(sport: /football/i).to_a

The reason for using the above syntax over:

User.where("users.sport LIKE ?", "%Football%").all

is that, like query will only work for SQL databases, while the regex based query suggested above will work for all SQL as well NoSQL database like mongodb.

Upvotes: 0

spickermann
spickermann

Reputation: 106962

To perform a LIKE query in Rails you can do this:

User.where("users.sport LIKE ?", "%Football%").all

Upvotes: 1

Related Questions