counter_cache has_​​many_through SQL优化,减少SQL查询的数量数量、counter_cache、SQL、many_through

2023-09-09 22:06:53 作者:戏子无情ぴ

我如何优化SQL查询,无视这样的情况:

How I can optimise my SQL queries, to ignore situations like this:

Meeting.find(5).users.size => SELECT COUNT(*)FROM ... WHERE ...

Meeting.find(5).users.size => SELECT COUNT(*) FROM ... WHERE ...

User.find(123).meetings.size => SELECT COUNT(*)FROM ... WHERE ...

User.find(123).meetings.size => SELECT COUNT(*) FROm ... WHERE ...

我不知道如何counter_cache在这里使用。

I have no idea how to use counter_cache here.

下面是我的模型关系:

class Meeting < ActiveRecord::Base
  has_many :meeting_users
  has_many :users, :through => meeting_users
end

class User < ActiveRecord::Base
  has_many :meeting_users
  has_many :meetings, :through => meeting_users
end

class Meeting_user < ActiveRecord::Base
  belongs_to :meeting
  belongs_to :user
end

什么是最优化的解决方案?

What are the most optimal solutions ?

和如何在这里实现counter_cache?

And how implement counter_cache here ?

推荐答案

据我知道你无法通过使用 counter_cache 的关联,这就是为什么你要手动增加它。

As far as I know you can't use counter_cache with through associations, that's why you should manually increment it.

例如(未经测试):

class MeetingUser < ActiveRecord::Base

  ...

  after_create { |record| 
    Meeting.increment_counter(:users_count, record.meeting.id)
  }

  after_destroy { |record| 
    Meeting.decrement_counter(:users_count, record.meeting.id)
  }

end