Rajesh Omanakuttan
Rajesh Omanakuttan

Reputation: 6918

SQL query IN using Ruby array

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;

Upvotes: 3

Views: 5803

Answers (2)

Peter Brown
Peter Brown

Reputation: 51697

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

Upvotes: 8

Aman Garg
Aman Garg

Reputation: 4218

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

@temp.join(',')

hopes, it will work.

Upvotes: 8

Related Questions