has_many:通过counter_cache
我的理解是,在定义:counter_cache选项时,它将在包含belongs_to声明的模型上指定。 因此,当使用has_may通过关联时,我有点不确定如何处理这个问题(因为我认为在这种情况下不使用belongs_to声明):
class Physician :appointments end class Appointment appointment_count end class Patient < ActiveRecord::Base end
我希望使用:counter_cache选项来更有效地查找属于医生的患者数量。
myPhysician.patients.count
仅供参考:Rails 3.1
干杯
我不确定你想要什么样的关系。 该示例类似于Rails指南中的示例
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
有许多Appointments
,并且有很多Patients
-
Appoinment
属于(有一名)Physician
和一名Patient
-
Patient
有许多Appointments
和许多Physicians
。
关于:counter_cache选项,根据belongs_to doc :如果您想要属于Physician
的Patients
数量,您需要:
class Appointment < ActiveRecord::Base belongs_to :physician, :counter_cache => :patient_count belongs_to :patient end
您需要编写一个迁移来将patient_count列添加到Phyisicans
表中。
但是, 对于has_many通过关系,Rails 3.1似乎会自动检测counter_cache列 ,因此您不必指定它(remove :counter_cache => :patient_count
)。 如果你指定它,你的计数器会上升两个(这很奇怪)。
顺便说一句,似乎存在一些问题:Rails 3.1中的counter_cache选项 ,如下所示:
考虑到所有这些,也许最好的办法是使用回调编写自己的计数机制。
希望能帮助到你 :)
我在一个has_many :through
添加了一个counter_cache
has_many :through
Rails 5.1上的关联,其理念与has_many
相同。 使用医生,预约,患者示例:
- 将
patients_count
作为整数添加到physicians
表中 - 将计数器缓存添加到连接模型(appointment.rb):
belongs_to :physician, counter_cache: :patients_count
注意:上面的答案是正确的,这个答案只是证实它适用于Rails 5.1。
- 从ruby中的哈希数组打印表到文件
- 如何格式化ruby logger?
- 我可以将哪些服务器端PDF呈现组件与.NET,PHP,Ruby等一起使用?
- 如何更改gem环境设置?
- 将XML集合(Pivotal Tracker故事)转换为Ruby散列/对象
- Rails 3:显示表单的validation错误(不保存ActiveRecord模型)
- 在Ruby中命名命名空间的首选方式(更好的样式)是什么? 单数还是复数?
- .gsub(/ \ … /,“”)。worub(/ \(/,“”)。gsub(/ \)/,“”)。gsub(/ \ localhost /,“”)<=这是少数
- 尝试使用Ruby Java Bridge(RJB)gem时出错“无法创建Java VM”