has_many :through with counter_cache

后端 未结 4 977
悲&欢浪女
悲&欢浪女 2020-12-06 09:40

It is my understanding that when defining a :counter_cache option it is to be specified on the model that includes the belongs_to declaration. So I am a little unsure of how

4条回答
  •  执笔经年
    2020-12-06 10:20

    I ran into a similar problem, counting the number of records in a two-deep relationship. In your example, this would be the number of Patients for a Physician, as opposed to the number of Appointments. (e.g. don't count multiple appointments for one patient) I haven't tested the other solutions offered, but it appears they return the number of appointments.

    I found no way to do this in Rails 4, primarily because there is no belongs_to through: option. After exhausting several fruitless approaches, I found gem counter_culture. This solved the problem easily, by defining a two-deep relationship to be counted:

    class Patient < ActiveRecord::Base
      belongs_to :appointment
      counter_culture [:appointment, :physician]
    end
    

    Add a counter field to Physician with:

    rails generate counter_culture Physician patients_count
    

    And voila! You can now do easy activerecord queries like:

    Physician.order(patients_count: 'DESC')
    

提交回复
热议问题