我相信这是 Rails 3 中的一个错误。我希望这里有人可以引导我朝着正确的方向前进。下面发布的代码纯粹是为了说明这个问题。希望这不会混淆这个问题。
鉴于我有一个 Post 模型和一个 Comment 模型。Post has_many Comments 和 Comment belongs_to Post。
在 Post 模型上设置 default_scope,定义 joins() 和 where() 关系。在这种情况下 where() 依赖于 joins()。
通常帖子不会依赖于评论。同样,我只想举一个简单的例子。当 where() 依赖于 joins() 时,这可能是任何情况。
class Post < ActiveRecord::Base
has_many :comments, :dependent => :destroy
default_scope joins(:comments).where("comments.id < 999")
end
class Comment < ActiveRecord::Base
belongs_to :post, :counter_cache => true
end
运行以下命令:
Post.update_all(:title => Time.now)
产生以下查询,并最终抛出 ActiveRecord::StatementInvalid:
UPDATE `posts` SET `title` = '2010-10-15 15:59:27' WHERE (comments.id < 999)
同样,update_all、delete_all、destroy_all 的行为方式相同。当我的应用程序在尝试更新 counter_cache 时抱怨时,我发现了这种行为。最终深入到 update_all。