From bea98cb44a6b35bc14a6e08fbc74a8deb24ac785 Mon Sep 17 00:00:00 2001 From: p31729568 Date: Fri, 21 Jun 2019 10:58:44 +0800 Subject: [PATCH] add course board message count rake --- app/models/message.rb | 7 +++---- lib/tasks/course_board_message_count.rake | 24 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 lib/tasks/course_board_message_count.rake diff --git a/app/models/message.rb b/app/models/message.rb index 26946f6d0..d3d507a72 100644 --- a/app/models/message.rb +++ b/app/models/message.rb @@ -56,11 +56,10 @@ class Message < ApplicationRecord from_board = Board.find(messages.first.board_id) root_ids = messages.map(&:id) - children = Message.where(parent_id: root_ids).select(:id).to_a - children_ids = children.map(&:id) - second_children = Message.where(parent_id: children_ids).select(:id).to_a + children_ids = Message.where(parent_id: root_ids).pluck(:id) + second_children_ids = Message.where(parent_id: children_ids).pluck(:id) - ids = root_ids.concat(children_ids).concat(second_children.map(&:id)).uniq + ids = root_ids.concat(children_ids).concat(second_children_ids).uniq ActiveRecord::Base.transaction do Message.where(id: ids, board_id: from_board.id).update_all(board_id: to_board.id) diff --git a/lib/tasks/course_board_message_count.rake b/lib/tasks/course_board_message_count.rake new file mode 100644 index 000000000..d1ac5524d --- /dev/null +++ b/lib/tasks/course_board_message_count.rake @@ -0,0 +1,24 @@ +namespace :course_board do + desc 'transfer children message to root message board' + task children_message_transfer: :environment do + Board.find_each do |board| + logger("Current transfer board id: #{board.id} ~") + + root_subquery = board.messages.where(parent_id: nil).reorder(nil).pluck(:id) + next if root_subquery.blank? + children_subquery = Message.where(parent_id: root_subquery).reorder(nil).pluck(:id) + next if children_subquery.blank? + second_children_subquery = Message.where(parent_id: children_subquery).reorder(nil).pluck(:id) + + ids = children_subquery.concat(second_children_subquery).uniq + Message.where(id: ids).update_all(board_id: board.id) + + Board.reset_counters(board.id, :messages) + logger("transfer success ~") + end + end + + def logger(msg) + puts msg + end +end \ No newline at end of file