xeroshogun
xeroshogun

Reputation: 1092

get multiple records in one query in ActiveRecord

Lets say I have a Cat table and each cat has a unique color. Is there an activerecord method I can use to get the red and the blue cat in one query. My goal is a faster query than having to find each one individually with Cat.where(color: red) then doing the same thing with blue.

Upvotes: 2

Views: 3267

Answers (3)

bakriawad
bakriawad

Reputation: 345

research JOIN statement

you can also use OR in where

where (color='blue' OR color='green')

check:

Join statement - toturialspoint.com

OR and AND expression

Upvotes: -1

boblin
boblin

Reputation: 3541

Cat.where(color: 'red').or.where(color: 'blue')

or

Cat.where("color = ? OR color = ?", "red", "blue")

or

Cat.where(color: ["red", "blue"])

Upvotes: 2

BroiSatse
BroiSatse

Reputation: 44685

You can do:

Cat.where(color: ['red', 'blue'])

this will generate SQL query:

SELECT cats.* FROM cats WHERE cats.color IN ('red', 'blue')

Upvotes: 7

Related Questions