4

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.

6

2 Answers 2

12
User.where(is_awesome: true, id: acceptable_ids)
Sign up to request clarification or add additional context in comments.

Comments

-3

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] )

7 Comments

Argument conversion should certainly be handed over to ActiveRecord. Doing otherwise is bad practice as it makes SQL injections more probable, especially with beginners.
I think you have an extra parenthesis in there right?
Thanks @DonnyP ... I think I was missing a closing parenthesis, just added it.
This answer is so bad I have to down vote it. Please look at the other answer to see how it should be done. You should never concatenate SQL queries by hand (possible SQL injection), and you should use what Rails gives you instead of reinventing the wheel...
You're definitely opening yourself up to SQL injection here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.