ruby SQL错误- ActiveRecord::StatementInvalid:PG::SyntaxError:误差

8yparm6h  于 12个月前  发布在  Ruby
关注(0)|答案(2)|浏览(122)

我在Rails上创建了一个构建SQL查询的方法,但是我得到了一个语法错误,不知道为什么,代码看起来是正确的。也许有人能找到问题所在?很可能是我没注意到的很明显的事情。
我的代码:

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

我得到的错误:

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 ()
fhity93d

fhity93d1#

我不知道为什么你需要SQL字符串,但通过两列过滤记录,你可以通过这个原则构建SQL查询:

SELECT * FROM table WHERE (column1, column2) IN ((valu11, value21), (valu12, value22));

这意味着你需要在字符串中使用内外括号
不要忘记清理SQL查询

def build_query(account_id:, word_group_id:, titles_locations_filters: [])
  base_query =
    ActiveRecord::Base.sanitize_sql(
      [
        <<~SQL.squish,
          SELECT * FROM word_group_values
          WHERE account_id = :account_id
          AND word_group_id <> :word_group_id
        SQL
        account_id:, word_group_id:
      ]
    )

  return base_query if titles_locations_filters.empty?

  title_locations =
    titles_locations_filters.map do |title, location|
      ActiveRecord::Base.sanitize_sql([
        '(:title, :location)', # inner brackets
        title:, location:
      ])
    end.join(', ')

  "#{base_query} AND (title, location) IN (#{title_locations})" # outer brackets
end

这样称呼它

account_id = 100
word_group_id = 200
titles_locations_filters = [%w[title1 location1], %w[title2 location2]]

build_query(account_id:, word_group_id:)
# SELECT * FROM word_group_values
# WHERE account_id = 100
# AND word_group_id <> 200

build_query(account_id:, word_group_id:, titles_locations_filters:)
# SELECT * FROM word_group_values
# WHERE account_id = 100
# AND word_group_id <> 200
# AND (title, location) IN (('title1', 'location1'), ('title2', 'location2'))
ff29svar

ff29svar2#

您的查询

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

因为info_arr是空的,所以你得到的是一个空字符串,这是一个无效的查询。
syntax error at or near ")正在抱怨空的()
你需要传递一个元组数组来使它有效。在这种情况下,普通字符串可能不起作用,除非info_arr是这样,但它是空的。

相关问题