加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 多态关系和计数器缓存

发布时间:2020-12-16 23:03:02 所属栏目:百科 来源:网络整理
导读:所以我有一个应用程序有2个不同的模型,评论和回复,每个你可以同意或不同意,所以我有一个名为Emotion的多态模型.这是我的代码: class Comment ActiveRecord::Base belongs_to :user has_many :replies has_many :emotions,:as = :emotionableendclass Reply
所以我有一个应用程序有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

所以这一切都很好,但是我需要为Comment和Reply添加一个计数器缓存,以便获得每个对象的Agrees和Disagree的大小.在所有文档中,它都有使用正常多态关联进行计数器缓存的示例,而不是具有额外条件的计数缓存.作为参考,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个计数器缓存.

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读