ruby-on-rails – 单表继承中的counter_cache
发布时间:2020-12-16 21:40:04 所属栏目:百科 来源:网络整理
导读:我想知道counter_cache是??否可以在单表继承中工作. 对于这些型号: class User has_many :questionsendclass Question belongs_to :user,:counter_cache = trueendclass SimpleQuestion Questionendclass ComplexQuestion Questionend 那么下面的计数器会起
我想知道counter_cache是??否可以在单表继承中工作.
对于这些型号: class User has_many :questions end class Question belongs_to :user,:counter_cache => true end class SimpleQuestion < Question end class ComplexQuestion < Question end 那么下面的计数器会起作用吗? create_table(:users) do |t| t.integer :questions_count t.integer :simple_questions_count t.integer :complex_questions_count end >所有这些都有效 哪一个?我猜第3次,但我还想要4次.如果不是4,我怎么做4工作? ===更新=== 这是一个例子: id,user_id,question_content,type 1,3,something,SimpleQuestion 2,SimpleQuestion 3,ComplexQuestion 所以现在我想: user.questions_count # => 3 user.simple_questions_count # => 2 user.complex_questions_count # => 1 我的问题是,什么是基本行为:counter_cache =>是的,是否可以应用于单表继承? 解决方法
查看实现“:counter_cache”的源代码,看起来它不支持您需要的计数.幸运的是,很容易在这里推出自己的.只需更新问题即可手动跟踪计数,如下所示:
class Question belongs_to :user after_create :increment_counts before_destroy :decrement_counts protected def increment_counts User.increment_counter :questions_count,user_id User.increment_counter "#{type.pluralize.underscore}_count",user_id end def decrement_counts User.decrement_counter :questions_count,user_id User.decrement_counter "#{type.pluralize.underscore}_count",user_id end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |