Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord: PG::Error: ERROR: column reference "created_at" is ambiguous

I am struggling with the error in object and not sure at all where is the problem.

This is how the models looks like:

class Car < ActiveRecord::Base  
  has_many :car_colors
  has_many :colors, :through => :car_colors
end

class CarColor < ActiveRecord::Base
  belongs_to :color
  belongs_to :car
end

class Color < ActiveRecord::Base  
  has_many :car_colors
  has_many :cars, :through => :car_colors
end

Here is the query:

@cars = Car.all(:joins => :car_colors, :conditions => { :car_colors => {:color_id => params[:id_number]}}, :order => "cars.created_at DESC")

And the error output:

PG::Error: ERROR:  column reference "created_at" is ambiguous
LINE 1: ...d" WHERE "car_colors"."color_id" = 2 AND (created_at...
                                                             ^
: SELECT "cars".* FROM "cars" INNER JOIN "car_colors" ON "car_colors"."car_id" = "cars"."id" WHERE "car_colors"."color_id" = 2 AND (created_at > '2013-05-03 12:28:36.551058') ORDER BY cars.created_at DESC

The generated SQL query (below the error message) seems to be fine, but what causes the error message?

Thank you in advance.

like image 899
user984621 Avatar asked Jun 03 '13 12:06

user984621


3 Answers

There likely is a created_at field in your car_colors table. created_at should probably be cars.created_at to remove the ambiguity.

like image 72
Denis de Bernardy Avatar answered Oct 30 '22 13:10

Denis de Bernardy


Define a scope like this:

scope :scope_age, -> { order(created_at: :desc) }

rather than:

scope :scope_age, -> { order("created_at DESC") }

It removes the ambiguity by using the property of the model in which the scope is defined in.

like image 27
Adam Waite Avatar answered Oct 30 '22 13:10

Adam Waite


Don't remove your timestamps from the join model, they aren't the problem - the problem is that something is adding a condition to your query:

AND (created_at > '2013-05-03 12:28:36.551058')

Since the date is one month ago, search your code for one.month.ago and see if it appears in any scopes, probably in your cars or car_colors models. Check the scopes manually if nothing turns up through the search.

Removing the timestamps will make your query work, but it's not the right thing to do.

like image 1
Matt Avatar answered Oct 30 '22 13:10

Matt