开发者

Why is this ActiveRecord statement failing in Server but not Console

开发者 https://www.devze.com 2023-03-26 04:53 出处:网络
I have the following query which is failing in rails s in a particular controller.It\'s not failing in rails c.

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

In开发者_JAVA技巧 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.


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"

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.

I feel pretty silly making this mistake, but hopefully this will help someone else who's running into the same issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消