0

我刚刚从 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 传递给查询时,为什么会被 id 过滤count?如何防止回调被此 id 限定范围?

4

0 回答 0