使用Ruby数组的SQL查询IN

时间:2013-08-18 16:38:00

标签: sql ruby-on-rails ruby arrays

我在ruby 2.0.0中有一个数组,@temp = [3, 4]我想在SQL IN语句中使用它。所以我希望删除括号([, ])。

我的SQL查询:

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;

2 个答案:

答案 0 :(得分:8)

如果要将其用作查询所在的字符串。你可以把它写成:

@temp.join(',')

希望,它会奏效。

答案 1 :(得分:8)

使用Active Record,您可以在使用“哈希条件”格式时直接使用数组,它会自动将其转换为正确的SQL:

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

请参阅Active Record查询的Rails指南"Subset Conditions" 2.3.3