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>
This commit is contained in:
Kane York 2020-04-20 10:03:25 -07:00 committed by GitHub
parent f63ac79b9d
commit ea8b40a53b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 4 deletions

View File

@ -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

View File

@ -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

View File

@ -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