Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Activerecord IN clause

I was wondering if anyone knew how to do an "IN" clause in activerecord. Unfortunately, the "IN" clause is pretty much un-googleable so I have to post here. Basically I want to answer a question like this "Give me all the college students that are in these dormitories where the dormitory id is in this array [id array]". I know how to write the query given a single dormitory id, but I don't know how to do it given an array of ids.

Any help is greatly appreciated. I'm sure this is a repost of a question somewhere, so I'll delete this once an answer/better search term is found.

like image 205
Black Dynamite Avatar asked Apr 16 '12 21:04

Black Dynamite


People also ask

What is ActiveRecord in Ruby on 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 ActiveRecord relation object?

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.

What is scope in Ruby on Rails?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.

What is ORM in Ruby on Rails?

ORM is Object Relational Mapper. It means you don't have to manually call the database yourself; the ORM handles it for you. Ruby on Rails uses one called ActiveRecord, and it's a really good one. ORM allows you to do things such as: User. find(50).contacts.


1 Answers

From §3.3.3 Subset Conditions of the Rails Guides:

If you want to find records using the IN expression you can pass an array to the conditions hash:

Customer.where(orders_count: [1,3,5]) 

This code will generate SQL like this:

SELECT * FROM customers WHERE (customers.orders_count IN (1,3,5)) 

You can also use the arel syntax:

Client.where(Client.arel_table[:order_count].in([1,3,5])) 

will generate the same SQL.

like image 91
Chen Kinnrot Avatar answered Sep 27 '22 19:09

Chen Kinnrot