Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

activerecord not like query

I could not find an activerecord equivalent of "Not Like". I was able to find a where.not, but that will check if a string does not match a value, as so:

User.where.not(name: 'Gabe')

is the same as:

User.where('name != ?', 'Gabe')

I was looking for a NOT LIKE, where the value is not contained in the string. The equivalent sql query would look like as follows:

SELECT * FROM users WHERE name NOT LIKE '%Gabe%'

In ActiveRecord I can currently get away with the following:

User.where("name NOT LIKE ?", "%Gabe%")

But that leaves a lot to be desired. Any new additions to Rails 4 to facilitate this?

like image 775
Donato Avatar asked Jun 08 '15 21:06

Donato


People also ask

What is not like SQL?

The NOT LIKE operator in SQL is used on a column which is of type varchar . Usually, it is used with % which is used to represent any string value, including the null character \0 . The string we pass on to this operator is not case-sensitive.

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

Can you use ActiveRecord without Rails?

ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.

What is eager loading in Rails?

Eager loading is a way to find objects of a certain class and a number of named associations. Here I share my thoughts on using it with Rails. What are N + 1 queries? It mainly occurs when you load the bunch of objects and then for each object you make one more query to find associated object.


1 Answers

Well, you can do something like:

User.where.not("name LIKE ?", "%Gabe%")

Note: This is only available in Rails 4.

like image 133
Arslan Ali Avatar answered Sep 25 '22 00:09

Arslan Ali