【问题标题】:Ambiguous column name error when upgrading to Rails 3.1升级到 Rails 3.1 时出现不明确的列名错误
【发布时间】:2012-03-14 19:11:42
【问题描述】:

下面的代码在 Rails 3 中运行良好,但会引发错误:

ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous column name: 
id: SELECT "categories".id FROM "categories" 
INNER JOIN "categorizations" 
ON "categories"."id" = "categorizations"."category_id" 
WHERE "categorizations"."reason_id" = 283 ORDER BY id

问题似乎是对 reason.category_ids 的调用

- reasons.each do |reason|
  - cat_ids = reason.category_ids.map {|id| "cat_id_#{id}"}.join(" ")
  %li{"data-reason-id" => reason.id, :class => cat_ids}
    %a= reason.text

class Reason < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations

更新: 在这里注释掉最后一行时,问题已解决。是bug吗?

class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :reasons, :through => :categorizations

  scope :active, where("active = ?", true)
  default_scope :order => 'id'

【问题讨论】:

  • 您在哪里订购? ORDER BY id 是模棱两可的部分,因为我认为 categoriescategorizations 都有一个 id 列。
  • 似乎问题出在 class Category 'id' 我该如何解决?
  • default_scope :order =&gt; 'categories.id' 解决了吗?
  • 注释掉它可以解决原来的问题。但出了什么问题?在 Rails 3.o 中一切正常。我如何在 3.1 中正确地使用 default_scope?
  • 进行了一些挖掘,但找到了它...查看答案。

标签: ruby-on-rails activerecord ruby-on-rails-3.1 sqlexception


【解决方案1】:

Here we go...

[In Rails 3.1] Supplying options hash to with_scope, with_exclusive_scope and default_scope has also been deprecated:

default_scope :order => "id DESC"

Try:

default_scope order('categories.id')

【讨论】:

    猜你喜欢
    • 2014-04-24
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多