1

I have on array like below,

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

I am trying to pass array in mysql where condition like below

 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)
1
  • 2
    Why don't you use ActiveRecord? Commented Jan 14, 2019 at 10:29

1 Answer 1

2

You are passing a string representation of the array to MySQL, which doesn't work. 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.

A better approach however is to not write the raw SQL at all, but rely on ActiveRecord to generate it. 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.

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

5 Comments

Hi jdno, Your answer solved my problem, Thank you very much.
What approach did you take? Raw SQL or ActiveRecord?
First I tried with ActiveRecord but it was giving data from only first table, so I took raw SQL approach. Thank you
@ManjunathC using ActiveRecord can give you both sets of data using includes(:quest_answers).references(:quest_answers) this will execute essentially the same as your raw sql but will also convert the return values to true AR objects.
Okay @engineersmnky thanks for your suggestion,I will try this.

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.