FEATURE: Add created_at column to user_badges (#9463)

FEATURE: Add created_at column to user_badges (#9463)

  • FEATURE: Add created_at column to user_badges

This makes scraping for newly granted badges easier.

Patch from @eviltrout applied.

Co-authored-by: Robin Ward robin.ward@gmail.com

diff --git a/app/serializers/user_badge_serializer.rb b/app/serializers/user_badge_serializer.rb
index 5ff9057..6f904b0 100644
--- a/app/serializers/user_badge_serializer.rb
+++ b/app/serializers/user_badge_serializer.rb
@@ -10,7 +10,7 @@ class UserBadgeSerializer < ApplicationSerializer
                :admin
   end
 
-  attributes :id, :granted_at, :count, :post_id, :post_number
+  attributes :id, :granted_at, :created_at, :count, :post_id, :post_number
 
   has_one :badge
   has_one :user, serializer: UserSerializer, root: :users
diff --git a/app/services/badge_granter.rb b/app/services/badge_granter.rb
index c6dfd82..26b9262 100644
--- a/app/services/badge_granter.rb
+++ b/app/services/badge_granter.rb
@@ -16,7 +16,8 @@ class BadgeGranter
     return unless badge.enabled?
 
     system_user_id = Discourse.system_user.id
-    user_badges = users.map { |u| { badge_id: badge.id, user_id: u.id, granted_by_id: system_user_id, granted_at: Time.now } }
+    now = Time.zone.now
+    user_badges = users.map { |u| { badge_id: badge.id, user_id: u.id, granted_by_id: system_user_id, granted_at: now, created_at: now } }
     granted_badges = UserBadge.insert_all(user_badges, returning: %i[user_id])
 
     users.each do |user|
@@ -325,8 +326,8 @@ class BadgeGranter
 
     sql = <<~SQL
       WITH w as (
-        INSERT INTO user_badges(badge_id, user_id, granted_at, granted_by_id, post_id)
-        SELECT :id, q.user_id, q.granted_at, -1, #{post_id_field}
+        INSERT INTO user_badges(badge_id, user_id, granted_at, granted_by_id, created_at, post_id)
+        SELECT :id, q.user_id, q.granted_at, -1, current_timestamp, #{post_id_field}
           FROM (
                  #{badge.query}
                ) q
diff --git a/db/migrate/20200417183143_add_created_at_to_badge_user.rb b/db/migrate/20200417183143_add_created_at_to_badge_user.rb
new file mode 100644
index 0000000..bbfd606
--- /dev/null
+++ b/db/migrate/20200417183143_add_created_at_to_badge_user.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+class AddCreatedAtToBadgeUser < ActiveRecord::Migration[6.0]
+  def up
+    add_column :user_badges, :created_at, :datetime, null: true
+    execute 'UPDATE user_badges SET created_at = granted_at WHERE created_at IS NULL'
+    change_column :user_badges, :created_at, :datetime, null: false, default: 'current_timestamp'
+  end
+
+  def down
+    remove_column :user_badges, :created_at
+  end
+end

GitHub sha: ea8b40a5

This commit appears in #9463 which was approved by eviltrout and eviltrout. It was merged by riking.