has_many :通过 counter_cache [英] has_many :through with counter_cache
问题描述
我的理解是,在定义 :counter_cache 选项时,它将在包含belongs_to 声明的模型上指定.所以我有点不确定在通过关联使用 has_may 时如何处理这个问题(因为我相信在这种情况下不使用belongs_to 声明):
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 to handle this when working with a has_may through association (as I believe that a belongs_to declaration is not used in this scenario):
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician, :counter_cache => appointment_count
end
class Patient < ActiveRecord::Base
end
我希望使用 :counter_cache 选项来更有效地查找属于医生的患者数量.
I wish to use the :counter_cache option to make finding the number of Patients belonging to a Physician more efficient.
myPhysician.patients.count
仅供参考:Rails 3.1
FYI: Rails 3.1
干杯
推荐答案
我不确定你想要什么样的关系.该示例类似于Rails 指南
I'm not sure what kind of relationship you want. That example is similar to the one in the Rails Guide
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
end
- 一个
Physician
有很多预约
,有很多Patients
- 一个
预约
属于(有一个)Physician
和一个Patient
- 一个
病人
有很多预约
和很多医师
. - A
Physician
has manyAppointments
, and has manyPatients
- An
Appoinment
belongs to (has one)Physician
and onePatient
- a
Patient
has manyAppointments
and manyPhysicians
.
关于 :counter_cache 选项,根据 belongs_to doc:如果您想要属于 Physician
的 Patients
数量,您需要:
Regarding the :counter_cache option, according to the belongs_to doc:
If you want the number of Patients
belonging to a Physician
you would need:
class Appointment < ActiveRecord::Base
belongs_to :physician, :counter_cache => :patient_count
belongs_to :patient
end
并且您需要编写迁移以将patient_count列添加到Phyisicans
表中.
And you need to write a migration to add the patient_count column to the Phyisicans
table.
但是,对于 has_many through 关系,Rails 3.1 似乎会自动检测 counter_cache 列,因此您不必指定它(删除 :counter_cache => :patient_count
).如果你指定它,你的计数器会增加两个(这很奇怪).
However, for has_many through relationships Rails 3.1 seems to automatically detect the counter_cache column, so you don't have to specify it (remove :counter_cache => :patient_count
). If you do specify it your counter will go up by two (this is very weird).
顺便说一下,Rails 3.1 中的 :counter_cache 选项似乎一些问题,如下所述:
By the way, there seems to be some problems with :counter_cache option in Rails 3.1, as reported here:
考虑到所有这些,也许最好的办法是使用回调编写自己的计数机制.
With all of that in mind, maybe your best bet is to write your own count mechanism using callbacks.
希望有帮助:)
这篇关于has_many :通过 counter_cache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!