【问题标题】:Polymorphic relationships and counter cache多态关系和计数器缓存
【发布时间】:2012-03-21 17:11:20
【问题描述】:

所以我有一个包含 2 个不同模型的应用程序,评论和回复,每个模型你都可以同意或不同意,所以我有一个名为 Emotion 的多态模型。这是我的代码:

class Comment < ActiveRecord::Base
  belongs_to :user
  has_many :replies
  has_many :emotions, :as => :emotionable
end



class Reply < ActiveRecord::Base
  belongs_to :user
  belongs_to :comment
  has_many :emotions, :as => :emotionable
end

class Emotion < ActiveRecord::Base
  belongs_to :emotionable, :polymorphic => :true  
end

所以这一切都很好,但是我需要为评论和回复添加一个计数器缓存,以便获得每个对象的同意和不同意的大小。在所有文档中,它都有使用正常多态关联进行计数器缓存的示例,而不是其中包含额外条件的示例。作为参考,Emotion 的模式如下所示:

create_table "emotions", :force => true do |t|
  t.integer  "user_id"
  t.string   "emotion"
  t.integer  "emotionable_id"
  t.string   "emotionable_type"
  t.datetime "created_at",       :null => false
  t.datetime "updated_at",       :null => false
end

TL:DR - 我需要能够通过计数器缓存在多态关联上调用@commet.agrees_count、@comment.disagrees_count、@reply.agrees_count 和@reply.disagrees_count。所以评论和回复需要 2 个计数器缓存。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 polymorphic-associations


    【解决方案1】:

    您可能希望将计数器缓存属性添加到关联类中的 attr_readonly 列表(例如 class Post; attr_readonly :cmets_count; end)。 http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to

    :polymorphic
    
        Specify this association is a polymorphic association by passing true. 
        Note: If you’ve enabled the counter cache, then you may
        want to add the counter cache attribute to the attr_readonly list in
        the associated classes 
        (e.g. class Post; attr_readonly :comments_count; end).
    

    【讨论】:

      【解决方案2】:

      我的建议是在 after_commit 回调中手动增加或减少您的计数器缓存,以便您可以测试记录是否被保留并在事务之外更新。这是因为它会使您的代码更加明确,并且在缓存更新或失效的方式和时间方面不那么神秘。

      如果您想在某些用户同意或不同意评论时给予他们更多的权限(例如业力系统),手动更新缓存也会为您提供额外的灵活性。

      【讨论】:

        【解决方案3】:

        这与“多态关系和计数器缓存”无关,是关于Multiple counter_cache in Rails model

        顺便说一下,对于“多态关系和计数器缓存”

        class Code < ActiveRecord::Base
          has_many :notes, :as => :noteable
        end
        
        class Issue < ActiveRecord::Base
          has_many :notes, :as => :noteable
        end
        
        class Note < ActiveRecord::Base
          belongs_to :noteable, polymorphic: true, counter_cache: :noteable_count
        end
        

        在您的表“问题”中,您应该有列“noteable_count”,与您的表“代码”相同

        【讨论】:

        • 是的,确实如此 - 您计算什么类型的关系并不重要,只需指定带有计数器的列并庆祝!
        • 你有一个类型。应该是counter_cache: :noteable_count
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-21
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        相关资源
        最近更新 更多