简体   繁体   English

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

[英]How to pass rails array mysql Where IN condition

I have on array like below, 我有下面的数组,

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

I am trying to pass array in mysql where condition like below 我正在尝试在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(', ')})")

But it did not work,How can pass an array to where In condition. 但是它没有用,如何将数组传递到条件所在的地方。

Error I am getting 我收到错误

  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)

You are passing a string representation of the array to MySQL, which doesn't work. 您正在将数组的字符串表示形式传递给MySQL,这是行不通的。 You need to insert the values in the array into the query. 您需要将数组中的值插入查询中。 This can be done by escaping the skills, and joining them: 这可以通过转义技能并加入他们来完成:

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

This produces 'ruby', 'Ruby on Rails' , which is a valid argument for the IN statement. 这将产生'ruby', 'Ruby on Rails' ,这是IN语句的有效参数。

A better approach however is to not write the raw SQL at all, but rely on ActiveRecord to generate it. 但是,更好的方法是根本不编写原始SQL,而是依靠ActiveRecord生成它。 This is the more maintainable and readable approach. 这是更易维护和易读的方法。

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

Passing an array to where converts it automatically into a subset condition . 将数组传递到where会将其自动转换为子集条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM