我最近刚刚从Rails 5.0升级到5.2,并且使用的回调之一似乎是通过原始查询ID来确定查询范围。这使我无法重新计算汇总统计信息。如何防止对回调进行范围划分?
例如,假设我有以下模型:
class Area < ActiveRecord::Base
has_many :posts,
through :area_posts
def count_area_posts
byebug
# some unrelated stuff
end
end
class Post < ActiveRecord::Base
has_many :areas,
through :area_posts
end
class AreaPost < ActiveRecord::Base
belongs_to :post
belongs_to :area
after_commit :update_area_status
def update_area_status
self.area.count_area_posts
end
end
如果我通过运行Area.count_area_posts
在AreaPost.where(id: 5).update(unrelated_thing: 10)
中达到断点,则在AreaPost
模型上的任何查询都会有一个附加的WHERE
子句,我没有明确包括:>
15: def count_area_posts
16: byebug
=> 17: # some unrelated stuff
18: end
19:end
(byebug) AreaPost.count
(15.3ms) SELECT COUNT(*) FROM "area_posts" WHERE "area_posts"."id" = $1 [["id", 5]]
1
(byebug)
但是,如果我一次更新每个AreaPost
:
@post.area_posts.each do |area_post|
area_post.update_attribute(unrelated_thing: 10) # this works as expected. AreaPost.count inside the callback is not scoped by id
end
AreaPost.count
查询不受ID限制:
15: def count_area_posts
16: byebug
=> 17: # some unrelated stuff
18: end
19:end
(byebug) AreaPost.count
(15.3ms) SELECT COUNT(*) FROM "area_posts"
182253
(byebug)
当我没有将ID传递给count
查询时,为什么用id过滤?如何防止此ID限制回调的作用?