Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rails 4 have support for OR queries

So in Rails 4 the long desired feature to use not queries has been added.

Article.where.not(title: 'Rails 3') 

Has similar support been added for or queries, or are they planning to make it. I couldn't find anything by browsing through the release notes.

Obviously I tried

Article.where(title: 'Rails 3').or(title: 'Rails 4') 

But that does not work.

like image 522
Arjan Avatar asked Jun 19 '13 13:06

Arjan


People also ask

What is eager loading rails?

Eager loading lets you preload the associated data (authors) for all the posts from the database, improves the overall performance by reducing the number of queries, and provides you with the data that you want to display in your views, but the only catch here is which one to use.

What are active records in Rails?

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.

What is an active record relation?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.


2 Answers

Article.where(title: ['Rails 3', 'Rails 4']) 

is how you'd do that in Active Record.

It's not possible to replicate any arbitrary SQL query using "Rails-y" syntax. But you can always just pass in literal sql.

So you could also do:

Article.where("articles.title = 'Rails 3' OR articles.title = 'Rails 4'") 
like image 161
gregates Avatar answered Oct 18 '22 16:10

gregates


This now works in Rails 5:

Article.where(title: 'Rails 3').or(Article.where(title: 'Rails 4')) 

Code example in Rails's source.

like image 38
Fellow Stranger Avatar answered Oct 18 '22 16:10

Fellow Stranger