meow
meow

Reputation: 28164

Storing multiple variable via a single db call

Hi folks, i find myself doing some variant of this often.

Essentially, i am doing 3 db calls, but I would like to do it in one single database call (for obvious performance reasons)

user1=User.find(x)
user2=User.find(y)
user3=User.find(z)

I believe there should be a simple rails method to handle this

I am using mongoid, but activerecord centric answers appreciated as well

Upvotes: 0

Views: 143

Answers (2)

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24617

users = User.find(1,2,3)

User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" IN (1, 2, 3)

UPDATE: If you want to store the result in the variables:

user1, user2, user3 = User.find(1,2,3)

Upvotes: 1

dee-see
dee-see

Reputation: 24078

users = User.find(x, y, z) will return an array with your results.

Documentation:

http://apidock.com/rails/ActiveRecord/Base/find/class

Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)

Upvotes: 0

Related Questions