Reputation: 63567
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
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