ruby-on-rails – has_many:通过counter_cache
我的理解是,当定义一个:counter_cache选项时,它将在包含belongs_to声明的模型上指定.所以我在使用has_may通过关联来处理这个问题有点不确定(因为我认为在这种情况下没有使用belongs_to声明):
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选项来查找属于医师的患者数量更有效率. myPhysician.patients.count FYI:Rails 3.1 干杯 解决方法
我不知道你想要什么样的关系.这个例子与
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 医师有很多预约,有很多患者 关于:counter_cache选项,根据belongs_to doc: 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选项,如下所示: > https://github.com/rails/rails/issues/3903 考虑到这一切,也许你最好的打算是使用回调编写自己的计数机制. 希望它有帮助:) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |