LovingRails
LovingRails

Reputation: 1575

Rails4 - ambiguous column name and no such column error

I have the following in my controller to list the users.

@users = User.paginate(:page => params[:page])

I tried to change the order using the following

@users = User.paginate(:page => params[:page]).order('created_at DESC')

I got the following error

ActiveRecord::StatementInvalid in UsersController#index
SQLite3::SQLException: ambiguous column name: created_at: SELECT DISTINCT "users"."id" FROM "users" LEFT OUTER JOIN "user_languages" ON "user_languages"."user_id" = "users"."id" WHERE (user_languages.level_id = 1) ORDER BY created_at DESC LIMIT 30 OFFSET 0

Then I changed the line as follows

@users = User.paginate(:page => params[:page]).order('user.created_at DESC')

and I am getting the following error.

ActiveRecord::StatementInvalid in UsersController#index
SQLite3::SQLException: no such column: user.created_at: SELECT DISTINCT "users"."id" FROM "users" LEFT OUTER JOIN "user_languages" ON "user_languages"."user_id" = "users"."id" WHERE (user_languages.level_id = 1) ORDER BY user.created_at DESC LIMIT 30 OFFSET 0

Kindly help to resolve this error.

Upvotes: 2

Views: 1127

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51191

You probably have some default scope on User that joins user_languages, and there is created_at column in both of these tables. So you should point out on which table's created_at you want to order:

@user = User.paginate(page: params[:page]).order('users.created_at DESC')

Upvotes: 4

Related Questions