Why does this ActiveRecord statement fail in the Server, but not the Console

I have the following query that does not work in rails s in a specific controller. This does not fail in rails c .

 Post.includes(:user).find(:all, :limit => 10, :order => 'users.display_name ASC') 

In the console, it returns the correct data. On 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 request is long and Iโ€™ll just include some 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 the controller, the request generates 3 additional terms. The request calls them t0_r9, t0_r10 and t0_r11. It seems that AR adds this because I refer to these specific columns in the representation of this controller action. I do not understand why this would do this, especially since the purpose of using includes .

+1
source share
1 answer

So the error was not in the code that I posted. I had an assistant to determine which column to order. 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" 

You Post.column_names know that this actually combines additional terms on Post.column_names . I fixed this problem by making a copy with Post.column_names.clone and this solved the problem.

I feel pretty stupid making this mistake, but hopefully this helps someone who is facing the same problem.

+1
source

Source: https://habr.com/ru/post/894148/


All Articles