微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

希望它有帮助:)

原文地址:https://www.jb51.cc/ruby/273384.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐