postgresql Rails ActiveRecord:PG::Error:错误:列引用“created_at”不明确
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16896937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails ActiveRecord: PG::Error: ERROR: column reference "created_at" is ambiguous
提问by user984621
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?
生成的 SQL 查询(在错误消息下方)似乎没问题,但是是什么导致了错误消息?
Thank you in advance.
先感谢您。
回答by Denis de Bernardy
There likely is a created_at field in your car_colors
table. created_at
should probably be cars.created_at
to remove the ambiguity.
您的car_colors
表中可能有一个 created_at 字段。created_at
应该是cars.created_at
为了消除歧义。
回答by Adam Waite
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.
它通过使用定义范围的模型的属性来消除歧义。
回答by Matt
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.
由于日期是一个月前,请搜索您的代码one.month.ago
并查看它是否出现在任何范围内,可能出现在您的汽车或 car_colors 模型中。如果通过搜索没有任何结果,请手动检查范围。
Removing the timestamps will make your query work, but it's not the right thing to do.
删除时间戳将使您的查询工作,但这不是正确的做法。