Search code examples
sqlruby-on-railsrubyrails-activerecord

SQL Syntax error - ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR


I created a method to build an SQL query on Rails, and I'm getting a syntax error, no idea why, the code looks correct to me. Maybe someone here is able to find the issue? It's likely something pretty obvious that I'm not noticing.

My code:

def build_query(info_arr)
  <<~SQL
     SELECT * FROM word_group_values WHERE account_id = :account_id
       AND word_group_id <> :word_group_id
       AND ("title", location) IN #{info_arr.join(', ')}
  SQL
end

The error I get:

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near ")" LINE 2: AND ("title", location) IN () ^ : SELECT * FROM word_group_values WHERE account_id = 110
 AND ("title", location) IN ()

Solution

  • Your query is

    SELECT * FROM word_group_values WHERE account_id = 110  AND ("title", location) IN ()
    

    Since info_arr is empty you are getting an empty string and this is an invalid query.

    (syntax error at or near ") is complaining about the empty ())

    You need to pass an array of tuples for it to be valid. A plain string will probably not work in this case, unless info_arr is that but is coming empty.