How do you do an or query in Rails 5 ActiveRecord? Also, is it possible to chain or with where in ActiveRecord queries?
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.
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.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With