PG::AmbiguousColumn:错误,即使我正在指定型号名称
PG::AmbiguousColumn: ERROR even tough I'm specifying the model name
我正在为模型构建范围以在集合中呈现某种随机性:
scope :biased_random, -> (value) {
self.select("*, RANDOM() * (to_char(created_at, 'YYYYMMDD')::float / to_char(now(), 'YYYYMMDD')::float) AS randomable_int").order(randomable_int: :desc)
}
我对结果很满意,但我得到了 PG::AmbiguousColumn: ERROR
:
"PG::AmbiguousColumn: ERROR: column reference \"created_at\" is ambiguous\nLINE 1: SELECT *, RANDOM() * (to_char(created_at, 'YYYYMMDD')::float...\n ^\n"
所以我尝试指定模型名称,因为它不应该再模糊了:
self.select("*, RANDOM() * (to_char(#{self.model.to_s.downcase}.created_at, 'YYYYMMDD')::float / to_char(now(), 'YYYYMMDD')::float) AS randomable_int").order(randomable_int: :desc)
现在我收到另一个 PG 错误:
ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near "model name")
(“型号名称”显然是我的型号)
我不明白为什么它一开始就模棱两可,然后为什么当我指定它时,我又遇到了另一个错误。
PG::AmbiguousColumn
错误很可能是因为您的查询连接了多个 table。
您需要在 created_at
前加上 table 的名称,而不是模型的名称 - https://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name 可能会有所帮助。
我正在为模型构建范围以在集合中呈现某种随机性:
scope :biased_random, -> (value) {
self.select("*, RANDOM() * (to_char(created_at, 'YYYYMMDD')::float / to_char(now(), 'YYYYMMDD')::float) AS randomable_int").order(randomable_int: :desc)
}
我对结果很满意,但我得到了 PG::AmbiguousColumn: ERROR
:
"PG::AmbiguousColumn: ERROR: column reference \"created_at\" is ambiguous\nLINE 1: SELECT *, RANDOM() * (to_char(created_at, 'YYYYMMDD')::float...\n ^\n"
所以我尝试指定模型名称,因为它不应该再模糊了:
self.select("*, RANDOM() * (to_char(#{self.model.to_s.downcase}.created_at, 'YYYYMMDD')::float / to_char(now(), 'YYYYMMDD')::float) AS randomable_int").order(randomable_int: :desc)
现在我收到另一个 PG 错误:
ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near "model name")
(“型号名称”显然是我的型号)
我不明白为什么它一开始就模棱两可,然后为什么当我指定它时,我又遇到了另一个错误。
PG::AmbiguousColumn
错误很可能是因为您的查询连接了多个 table。
您需要在 created_at
前加上 table 的名称,而不是模型的名称 - https://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name 可能会有所帮助。