Commit bf2d5420 authored by 2458773093's avatar 2458773093

group member count optimization

parent bd3f453c
......@@ -15,6 +15,7 @@
# is_archived :boolean default(FALSE), not null
# created_at :datetime not null
# updated_at :datetime not null
# member_count :integer default(0)
#
class Group < ApplicationRecord
......
......@@ -21,10 +21,20 @@ class GroupAccount < ApplicationRecord
validates :account_id, uniqueness: { scope: :group_id }
after_commit :remove_relationship_cache
after_create :increment_member_count
after_destroy :decrement_member_count
private
def remove_relationship_cache
Rails.cache.delete("relationship:#{account_id}:group#{group_id}")
end
def increment_member_count
group&.increment!(:member_count)
end
def decrement_member_count
group&.decrement!(:member_count)
end
end
......@@ -22,8 +22,4 @@ class REST::GroupSerializer < ActiveModel::Serializer
full_asset_url(object.cover_image.url)
end
def member_count
object.accounts.count
end
end
class AddMemberCountToGroups < ActiveRecord::Migration[5.2]
def up
add_column :groups, :member_count, :integer
change_column_default :groups, :member_count, 0
end
def down
remove_column :groups, :member_count
end
end
class BackfillAddMemberCountToGroups < ActiveRecord::Migration[5.2]
disable_ddl_transaction!
def change
Group.in_batches do |relation|
relation.update_all member_count: 0
sleep(0.1)
end
end
end
......@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2019_07_21_234917) do
ActiveRecord::Schema.define(version: 2019_07_22_003649) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
......@@ -358,6 +358,7 @@ ActiveRecord::Schema.define(version: 2019_07_21_234917) do
t.boolean "is_archived", default: false, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "member_count", default: 0
t.index ["account_id"], name: "index_groups_on_account_id"
end
......
# frozen_string_literal: true
task fix_group_member_counts: 'gabsocial:fix-group-member-counts'
namespace :gabsocial do
desc 'Re-compute group member counts'
task :fix_group_member_counts => :environment do
Group.select(:id).all.each do |group|
group.update_column(:member_count, group.accounts.count)
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment