counter_cache has_many_through sql optimisation, reduce number of sql queries

前端 未结 2 1847
北恋
北恋 2020-12-29 16:26

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

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

User.find(1

相关标签:
2条回答
  • 2020-12-29 16:40

    Starting from Rails3.0.5 and in newer versions, you are now able to set counter cache to the "linker" model, in your case it will be:

    class MeetingUser < ActiveRecord::Base
      belongs_to :meeting, :counter_cache => :users_count
      belongs_to :user, :counter_cache => :meetings_count
    end
    

    It's important to explicitly specify count column names, otherwise the columns used will default to meeting_users_count.

    0 讨论(0)
  • 2020-12-29 16:43

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

    For example (untested):

    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
    
    0 讨论(0)
提交回复
热议问题