Don P
Don P

Reputation: 63567

Get all Rails records from an array of IDs

I have an array of record IDs ["303", "430", "4321", "5102"]. I want to get all records that match these IDs, using SQL:

acceptable_ids = ["303", "430", "4321", "5102"]
@users = User.where("is_awesome = true AND id IN acceptable_ids)

Gives this error:

ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR:  syntax error at or near "["

What is the correct way to write my query to get all users with ids that match acceptable_ids?

Note:

I am aware of User.find(acceptable_ids), but can't use this since I am constructing a SQL query with select, where, and join clauses.

Upvotes: 4

Views: 4614

Answers (2)

SteveTurczyn
SteveTurczyn

Reputation: 36860

You could do this.

@users = User.where("is_awesome = true AND id IN (#{acceptable_ids.join(', ')})")

I'm sure I've seen a simpler way but can't recall it at the moment... but above should work.

EDIT

However, you can see from the vociferous comments that this is not a popular answer, so you should look at some of the alternatives linked and listed, e.g.

# Will raise exception if any value not found
User.find( [1,3,5] )

# Will not raise an exception
User.find_all_by_id( [1,3,5] )

Upvotes: -3

Kyle Decot
Kyle Decot

Reputation: 20815

User.where(is_awesome: true, id: acceptable_ids)

Upvotes: 12

Related Questions