Ruby on rails 我可以在一个型号上有两个计数器缓存吗?
我有一个用户模型和一个Imagevote模型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
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指南中的选项。。我不知道您可以指定自定义列名。对我来说更优雅。再次非常感谢你,科蒂。