Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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%')
like image 367
user659068 Avatar asked Mar 14 '11 18:03

user659068


People also ask

When condition in Ruby?

Ruby compares the object in the when clause with the object in the case clause using the === operator. For example, 1.. 5 === x , and not x === 1..

What does =~ mean in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

How to check if a condition is true in Ruby?

With an if statement you can check if something is true . But when you want to check for the opposite “not true” (false) there is two things you can do. You can reverse the value with ! . Remember, using unless in Ruby is just the reverse of using if.

What does .first mean in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.


2 Answers

Person.where('name LIKE ?', '%egm%').all
like image 51
Jakub Hampl Avatar answered Oct 16 '22 08:10

Jakub Hampl


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}%"})
like image 26
Mike Lewis Avatar answered Oct 16 '22 07:10

Mike Lewis