ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: “AS”处或附近的语法错误

问题描述 投票:0回答:0

我想知道是否有人可以解释为什么我在 ActiveRecord SQL 注入中收到此错误,但当我添加

.to_a
时测试通过了?我将 PostgreSQL 与 Ruby on Rails 和 RSpec 一起使用。

def top_5_authors
  books.joins(review: :author)
    .where('books.title = ?', 'reviewed')
    .select("CONCAT(authors.first_name,' ', authors.last_name) AS full_name, COUNT(books.id) AS         book_count")
    .group('full_name')
    .order('book_count DESC')
    .limit(5)
    # .to_a
end

这是我注释掉时的错误信息

.to_a
:

ActiveRecord::StatementInvalid:
     PG::SyntaxError: ERROR:  syntax error at or near "AS"
     LINE 1: ...AT(authors.first_name,' ', authors.last_name) AS full_na...
                                                                    ^

似乎将查询作为数组返回会覆盖语法错误,可能与我使用

.select
CONCAT
处的SQL注入有关。但是,我尝试了多种不使用 CONCAT 且不使用别名
full_name
的组合,然后在
AS book_count
处抛出错误。我也尝试过不使用该别名并进行相应的重构。

在这两种情况下,当我添加

.to_a
时效果很好。

我相信我正在使用正确的语法进行查询,可能是错误的,因为 SQL 和 ActiveRecord 对我来说都是新的,但是当使用

.to_a
时,它工作正常,我可以访问我需要的数据。我现在只是不明白为什么。任何想法都会受到欢迎。谢谢你。

activerecord syntax-error sql-injection
© www.soinside.com 2019 - 2024. All rights reserved.