Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use OR condition in ActiveRecord query

I want to grab all the users that either have an email as the one supplied or the first and last name. So for example:

users = User.where(:first_name => "James", :last_name => "Scott") 

which will return all the users that have the first and last name of "James" & "Scott".

users = User.where(:email => "[email protected]") 

which will return the user with the email as "[email protected]".

Is there a way to do a where clause to return either the users with the same first and last name and the user with the email that matches in one where query or do I need to do a merge on the 2 separate where clauses.

like image 930
Matt Elhotiby Avatar asked Jun 03 '12 14:06

Matt Elhotiby


People also ask

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

Can you use ActiveRecord without rails?

One of the primary aspects of ActiveRecord is that there is very little to no configuration needed. It follow convention over configuration. 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 does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is ActiveRecord in Ruby?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

Rails 5 comes with an or method.

This method accepts an ActiveRecord::Relation object. eg:

User.where(first_name: 'James', last_name: 'Scott')     .or(User.where(email: '[email protected]')) 
like image 187
Santhosh Avatar answered Sep 23 '22 13:09

Santhosh