Mysql2 :: Error: column "created_at" in order order is ambiguous

I have the following query that works correctly

ObjectItem.find(:all, :include => :object_groups, :conditions =>  "object_items.description LIKE '%#{search}%' OR object_groups.description LIKE '%#{search}%'", :order => 'object_items.created_at DESC')

But running the request this way is now deprecated, so I'm trying to move on to this form

ObjectItem.order('object_items.created_at DESC').includes(:object_groups).where("object_items.description LIKE '%#{search}%' OR object_groups.description LIKE '%#{search}%'")

But I get the following error:

Mysql2::Error: Column created_at in order clause is ambiguous: SELECT  DISTINCT `object_items`.id FROM `object_items` LEFT OUTER JOIN `object_groups_object_items` ON `object_groups_object_items`.`object_item_id` = `object_items`.`id` LEFT OUTER JOIN `object_groups` ON `object_groups`.`id` = `object_groups_object_items`.`object_group_id` WHERE (object_items.description LIKE '%%' OR object_groups.description LIKE '%%') ORDER BY object_items.created_at DESC, created_at DESC  LIMIT 20 OFFSET 0
+3
source share
6 answers

order ('users.created_at DESC')

The main problem is that there is probably a connection request, so there is a created_at field in the table, so it throws an error. if you want to order the result, according to which tables are created, using the table_name.field_name on which you order the result.

+12
source
ORDER BY object_items.created_at DESC, created_at DESC LIMIT 20 OFFSET 0

, "created_at", .

, .order - , - . object_items.created_at, .

+1

: order ('users.created_at DESC') order (created_at:: asc)

+1

, .

object_items, object_groups "created_at".

(-) (), .

0

object_groups ObjectItem?

ORDER BY created_ar DESC can be added to the query if you have a relationship similar to the following in the ObjectItem:

has_many :object_groups, :order => "created_at DESC"
0
source

I came across this today in a Spree project. This is almost always due to the fact that the table name is not specified in the order clause. See this ticket as I solved the problem: https://github.com/spree/spree/issues/2654

In my case, I added a decorator to one of my spree models, and it added the order clause without the corresponding table name.

-1
source

All Articles