gpt4 book ai didi

sql - 将 select 方法与第一个方法组合返回错误 rails 4

转载 作者:行者123 更新时间:2023-11-29 12:21:13 24 4
gpt4 key购买 nike

我在模型的范围内有一个 select 语句,如下所示:

scope :unanswered, -> {includes(:votes).select("posts.*, sum(votes.choice) AS up_vote").order("up_vote ASC").group("votes.id, posts.id").references(:votes)}

这很好用,但是当我结合 first 方法时,如:Model.unanswered.first,我遇到了 SQL 错误。

Rails 生成的 SQL 如下:

SELECT  DISTINCT "posts"."id", up_vote AS alias_0 FROM "posts" LEFT OUTER JOIN "votes" ON "votes"."post_id" = "posts"."id" WHERE "posts"."type" IN ('Model') GROUP BY votes.id, posts.id  ORDER BY up_vote ASC LIMIT 1

错误:

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "up_vote" does not exist
LINE 1: SELECT DISTINCT "posts"."id", up_vote AS alias_0 FROM "post...

我使用的是 (PostgreSQL) 9.1.12

这是否是 Rails 错误?

方案表:

create_table "votes", force: true do |t|
t.integer "user_id"
t.integer "post_id"
t.integer "choice"
t.datetime "created_at"
t.datetime "updated_at"
end

最佳答案

用作

Model.unanswered[0] 

代替 Model.unanswered.first

当你说 Model.unanswered.first 内部 rails activerecord adds LIMIT 1 到你的查询并且它找不到别名 up_vote 误解它作为列名。

当您使用 Model.unanswered[0] 时,查询会被正确触发(不添加任何 LIMIT 1)并且由于返回结果是一个数组,您可以拉取通过指定索引零即第一个元素,[0]

关于sql - 将 select 方法与第一个方法组合返回错误 rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22764534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com