Martin
Martin

Reputation: 11336

Searching from a range of ids in ActiveRecord

How can I do something like this in range?

User.find(14000..14500)

I need to choose a certain range of Users starting and finishing on specifics ids.

Upvotes: 28

Views: 18330

Answers (4)

KARASZI István
KARASZI István

Reputation: 31467

You can use the where method:

User.where(id: 14000..14500)

Explanation

The where method here receives a hash argument in its shortened form, where the value for the id key is a Range.

Upvotes: 67

mikowiec
mikowiec

Reputation: 501

You can use range definition for scoped:

User.find(1)       # returns the object for ID = 1
User.find([1])

User.find(1, 2, 9) # returns an array for objects with IDs in (1, 2, 9)
User.find([1, 2, 9])

User.scoped(:conditions => { :id => 1..9})

Upvotes: 2

blawzoo
blawzoo

Reputation: 2485

You can do it like this too:

User.find_by_id(14000..14500)

Upvotes: 7

Arvind singh
Arvind singh

Reputation: 1392

Try this also

User.find((start..end).to_a)

Ex -

User.find((14000..14500).to_a)

Upvotes: 2

Related Questions