From e5855f7fd2657574c5af99890c63d530ca3bb5d0 Mon Sep 17 00:00:00 2001 From: Mark Longair Date: Mon, 19 Aug 2013 10:34:05 +0100 Subject: Improve calculation of PublicBody statistics columns On PublicBody, we don't need to update info_requests_count because that's already done with :counter_cache. On the other hand, info_requests_successful_count and info_requests_not_held_count can't be updated easily with counter_cache (since they need conditions to be attached). Instead we update them in post_save and post_destroy, as suggested here: http://blog.douglasfshearer.com/post/17495285851/custom-counter-cache-with-conditions This also adds tests to ensure that the after_(save|destroy) callbacks are called and that they modify the counts correctly. --- app/models/info_request.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'app/models/info_request.rb') diff --git a/app/models/info_request.rb b/app/models/info_request.rb index 9bce2ca88..91bd37d9f 100644 --- a/app/models/info_request.rb +++ b/app/models/info_request.rb @@ -1125,6 +1125,17 @@ public end end + after_save :update_counter_cache + after_destroy :update_counter_cache + def update_counter_cache + self.public_body.info_requests_not_held_count = InfoRequest.where( + :public_body_id => self.public_body.id, + :described_state => 'not_held').count + self.public_body.info_requests_successful_count = InfoRequest.where( + :public_body_id => self.public_body.id, + :described_state => ['successful', 'partially_successful']).count + end + def for_admin_column self.class.content_columns.map{|c| c unless %w(title url_title).include?(c.name) }.compact.each do |column| yield(column.human_name, self.send(column.name), column.type.to_s, column.name) -- cgit v1.2.3