Ruby on rails 多态关系与计数器缓存
所以我有一个应用程序,有两种不同的模式,评论和回复,每个模式你可以同意也可以不同意,所以我有一个叫做情感的多态模式。以下是我的代码:Ruby on rails 多态关系与计数器缓存,ruby-on-rails,ruby-on-rails-3,polymorphic-associations,Ruby On Rails,Ruby On Rails 3,Polymorphic Associations,所以我有一个应用程序,有两种不同的模式,评论和回复,每个模式你可以同意也可以不同意,所以我有一个叫做情感的多态模式。以下是我的代码: class Comment < ActiveRecord::Base belongs_to :user has_many :replies has_many :emotions, :as => :emotionable end class Reply < ActiveRecord::Base belongs_to :user
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
TL:DR-我需要能够通过计数器缓存对多态关联调用@commet.agreements\u count、@comment.disagreements\u count、@reply.agreements\u count和@reply.disagreements\u count。因此,评论和回复将需要2个计数器缓存。我的建议是在提交后回调中手动增加或减少计数器缓存,以便您可以测试记录是否被持久化,以及它是否在事务之外更新。这是因为它将使您的代码更加明确,并且在缓存更新或失效的方式和时间上不那么神秘
此外,手动更新缓存还为您提供了额外的灵活性,例如,如果您希望在某些用户同意或不同意评论(如karma systems)时给予他们更大的权限。您可能希望将计数器缓存属性添加到相关类中的attr\u只读列表中(如class Post;attr\u readonly:comments\u count;end).
这与“多态关系和计数器缓存”无关,而是关于 顺便说一下,对于“多态关系和计数器缓存”
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
类代码:notable
结束
类问题:notable
结束
类注释
在表'issues'中,您应该有一列'noteable_count',与表'codes'相同。这应该可以工作是的,这是真的-您计算的关系类型不重要,只需指定带有计数器的列并庆祝即可!你有一种类型。应该是
counter\u cache::notable\u count
: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).
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