3

I have an array in ruby 2.0.0, @temp = [3, 4] which I want to use in SQL IN statement. So I want the brackets ([, ]) to be removed.

My SQL query:

SELECT E.id,E.name, CEU.attempt, E.total_mark, CEU.has_attended as attendance, CE.id as categoryexamId, CE.examtype_id as examType, CU.id as categoryuserId, U.name as username

      FROM exams E
      Inner Join categoryexams CE on E.id = CE.exam_id
      Inner Join categoryexamusers CEU on CE.id = CEU.categoryexam_id
      Inner Join categoryusers CU on CEU.categoryuser_id = CU.id
      Inner Join categories C on CE.category_id = C.id
      Inner Join users U on CU.user_id = U.id
      Inner Join examtypes ET on CE.examtype_id = ET.id
      WHERE CE.category_id = #{category_id} AND CEU.has_attended = 1 AND U.id = #{user} AND CE.currentyear = #{academicYear} AND CE.examtype_id = #{examtype}" + (@temp.blank? ? "" : " AND CEU.categoryexam_id NOT IN (#{@temp})") +
      " Group By CE.id;
3

2 Answers 2

8

With Active Record, you can just use the array directly when using the "hash conditions" format, and it will automatically convert it to the right SQL:

MyModel.where(column: [3, 4])

See the Rails Guide on Active Record querying "Subset Conditions" 2.3.3

Sign up to request clarification or add additional context in comments.

1 Comment

Use Rails Active Record to create your queries as often as possible. This protects you from SQL injection attacks.
8

If you want to use this as a string in where query. You can write it as:

@temp.join(',')

hopes, it will work.

2 Comments

-1 This allows adding further potential SQL injections to the query.
How do you even know the query will face user inputs ?

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.