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
> https://github.com/rails/rails/issues/3085

考虑到这一切,也许你最好的打算是使用回调编写自己的计数机制.

希望它有帮助:)

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...