user659068
user659068

Reputation: 343

Like and where condition in ruby

What is the syntax for like in Ruby on Rails? This is something I'm trying to do:

I am trying to find all the last name from table which starts with egm so something like %egm%. I know how to do using find_by_sql but just curious to know the Ruby way.

s = Person.find_by_last_name('nan%')

Upvotes: 15

Views: 18022

Answers (3)

Brian Glick
Brian Glick

Reputation: 2201

To expand a bit, the find_by_X methods use the = operator, so you wouldn't want to use them for a like condition. The "Rails" way involves using a bit of SQL inside of the where method as shown in the other answers. The same would apply if you're trying to sort your results using the order method.

Upvotes: 3

Mike Lewis
Mike Lewis

Reputation: 64147

l_name_var = "nan"
Person.where("people.last_name LIKE :l_name", {:l_name => "#{l_name_var}%"})

or in your case

l_name_var = "egm"
Person.where("people.last_name LIKE :l_name", {:l_name => "%#{l_name_var}%"})

Upvotes: 13

Jakub Hampl
Jakub Hampl

Reputation: 40543

Person.where('name LIKE ?', '%egm%').all

Upvotes: 19

Related Questions