Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails: Update Comments Count for All Topics in a Group

Rails: Update Comments Count for All Topics in a Group

def update_topics_comments_count
  begin
    ActiveRecord::Base.connection.execute <<~SQL
      UPDATE topics
         SET comments_count = (SELECT count(1)
                                 FROM topic_comments
                                WHERE topic_comments.topic_id = topics.id
                                  AND topics.group_id = '#{group.id}')
    SQL
  ensure
    ActiveRecord::Base.connection.close
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.