Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5: ActiveRecord OR query

How do you do an or query in Rails 5 ActiveRecord? Also, is it possible to chain or with where in ActiveRecord queries?

like image 895
K M Rakibul Islam Avatar asked Sep 24 '15 04:09

K M Rakibul Islam


People also ask

What is Rails ActiveRecord?

What is ActiveRecord? 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.

What does ActiveRecord return?

Active Record objects can be created from a hash, a block, or have their attributes manually set after creation. The new method will return a new object while create will return the object and save it to the database. A call to user.

What is ActiveRecord base?

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

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.


2 Answers

The ability to chain or clause along with where clause in ActiveRecord query will be available in Rails 5. See the related discussion and the pull request.

So, you will be able to do the following things in Rails 5:

To get a post with id 1 or 2:

Post.where('id = 1').or(Post.where('id = 2')) 

Some other examples:

(A && B) || C:

    Post.where(a).where(b).or(Post.where(c)) 

(A || B) && C:

    Post.where(a).or(Post.where(b)).where(c) 
like image 98
K M Rakibul Islam Avatar answered Sep 18 '22 21:09

K M Rakibul Islam


We don't need to wait for rails 5 to use this OR query. We can also used it with rails 4.2.3. There is a backport here.

Thank to Eric-Guo for gem where-or, Now we can add this OR functionality in >= rails 4.2.3 also using this gem.

like image 45
Dipak Gupta Avatar answered Sep 19 '22 21:09

Dipak Gupta