Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 我可以在一个型号上有两个计数器缓存吗?_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 我可以在一个型号上有两个计数器缓存吗?

Ruby on rails 我可以在一个型号上有两个计数器缓存吗?,ruby-on-rails,ruby-on-rails-4,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: :destro

我有一个用户模型和一个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
class-Imagevote
我可以在用户模型中为“投票计数”和“投票计数”属性设置计数器缓存吗

如果是,我应该这样做:

class Imagevote < ActiveRecord::Base
        belongs_to :voter, class_name: "User", :counter_cache => true
        belongs_to :voted, class_name: "User", :counter_cache => true
class-Imagevotetrue
属于:投票,类名称:“用户”,计数器缓存=>true

我是否需要笨拙地将新属性命名为“voteds_count”和“Votters_count”,或者上述功能是否有效?

是的,您可以按以下方式执行:

    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"
如果要指定自定义列名,请按如下操作:

    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指南中的选项。

。我不知道您可以指定自定义列名。对我来说更优雅。再次非常感谢你,科蒂。