这是为什么ActiveRecord的声明服务器而不是控制台失败 [英] Why is this ActiveRecord statement failing in Server but not Console
问题描述
我有以下的查询,它失败在轨道小号
在一个特定的控制器。这不是失败在轨ç
。
I have the following query which is failing in rails s
in a particular controller. It's not failing in rails c
.
Post.includes(:user).find(:all, :limit => 10, :order => 'users.display_name ASC')
在控制台返回正确的数据。在服务器中,我得到这个错误
In the console it returns the correct data. In the server, I get this error
ActiveRecord::StatementInvalid: PGError: ERROR: column posts.users.display_name does not exist
LINE 1: ...s_count" AS t0_r7, "posts"."popularity" AS t0_r8, "posts"."u...
^
查询是漫长的,我就包括一些相关片段
The query is long and I'll just include a few relevant snippets
: SELECT "posts"."id" AS t0_r0, "posts"."post_content" AS t0_r1,
...
"posts"."popularity" AS t0_r8, "posts"."users.display_name" AS t0_r9,
"posts"."subtopics.name" AS t0_r10, "posts"."categories.category_name"
AS t0_r11
...
FROM "posts" LEFT OUTER JOIN "users" ON "users"."id" = "posts"."user_id"
ORDER BY users.display_name ASC LIMIT 10
在控制器中,查询生成3个额外的条款。查询标签他们作为t0_r9,t0_r10和t0_r11。这似乎是AR的增加,是因为我引用这些特定的列在该控制器操作的视图。我不明白为什么它会做到这一点,虽然,因为这是使用包括
。
In the controller, the query generates 3 extra terms. The query labels them as t0_r9, t0_r10, and t0_r11. It seems like AR is adding this because I'm referencing those specific columns in the view of that controller action. I don't see why it'd do that, though, as that's the purpose of using includes
.
推荐答案
因此,错误不是在code我张贴。我有一个助手来确定命令的列。它看起来是这样的:
So the error wasn't in the code I posted. I had a helper to determine which column to order by. It looked something like this:
valid_names = Post.column_names
valid_names = valid_names.concat(["users.display_name", "subtopics.name",
"categories.category_name"])
valid_names.include?(params[:sort]) ? params[:sort] : "popularity"
我一点也不知道,这实际上将串联额外的条件到 Post.column_names
。我通过做副本 Post.column_names.clone
修复了这个问题,这解决了问题。
Little did I know that this would actually concatenate the extra terms onto Post.column_names
. I fixed this issue by making a copy with Post.column_names.clone
and this resolved the issue.
我觉得pretty的愚蠢犯这种错误,但希望这会帮助别人谁是运行到了同样的问题。
I feel pretty silly making this mistake, but hopefully this will help someone else who's running into the same issue.
这篇关于这是为什么ActiveRecord的声明服务器而不是控制台失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!