如何在Rails数组中传递MySQL where IN条件

时间:2019-01-14 10:24:25

标签: ruby-on-rails ruby

我在数组如下,

 skills = ['ruby','Ruby on Rails'];

我正在尝试在条件如下的mysql中传递数组

 questions =  MysqlConnection.connection.select_all("
                   SELECT questions.*,quest_answers.* FROM `questions` 
                   INNER JOIN `quest_answers` ON `quest_answers`.`question_id` = 
                  `questions`.`id` where questions.category IN (#{skills.join(', ')})")

但是它不起作用,如何将数组传递给In条件。

我遇到错误

  Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'on rails,  Ruby)' at line 1:  SELECT questions.*,quest_answers.* FROM `questions` INNER JOIN `quest_answers` ON `quest_answers`.`question_id` = `questions`.`id` where questions.category IN (Ruby on rails,  Ruby)

1 个答案:

答案 0 :(得分:2)

您正在将数组的字符串表示形式传递给MySQL,这是行不通的。您需要将数组中的值插入查询中。这可以通过转义技能并加入他们来完成:

skills.map { |s| "'#{s}'" }.join(', ')

这将产生'ruby', 'Ruby on Rails',它是IN语句的有效参数。

但是,更好的方法是根本不编写原始SQL,而是依靠ActiveRecord生成它。这是更易于维护和可读的方法。

Question.joins(:quest_answers).where(category: skills)

将数组传递给where会自动将其转换为subset condition