我可以在一个型号上有两个counter_caches吗?

时间:2014-03-21 16:48:13

标签: ruby-on-rails ruby-on-rails-4

我有一个用户模型和一个Imagevote模型。

class Imagevote < ActiveRecord::Base
    belongs_to :voter, class_name: "User"
    belongs_to :voted, class_name: "User"

class User < ActiveRecord::Base
  has_many :imagevotes, foreign_key: "voted_id", dependent: :destroy
  has_many :reverse_imagevotes, foreign_key: "voter_id", dependent: :destroy

我可以在User模型中为'voted_count'和'voter_count'属性设置counter_caches吗?

如果是,我应该这样做:

class Imagevote < ActiveRecord::Base
        belongs_to :voter, class_name: "User", :counter_cache => true
        belongs_to :voted, class_name: "User", :counter_cache => true

我是否需要笨拙地将新属性命名为'voteds_count'和'votes_count',或者将上述工作命名?

1 个答案:

答案 0 :(得分:1)

是的,您可以按照以下方式执行此操作:

    belongs_to :voter, class_name: "User", :counter_cache => true
    belongs_to :voted, class_name: "User", :counter_cache => true

如果要指定自定义列名,请按以下步骤操作:

    belongs_to :voter, class_name: "User", :counter_cache => "voter_count"
    belongs_to :voted, class_name: "User", :counter_cache => "voted_count"

在Rails指南中了解 counter_cache 选项。