ぼざクリタグ広場 https://hub.nizika.monster
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

76 lines
2.5 KiB

  1. class CreatePostVersions < ActiveRecord::Migration[8.0]
  2. class Post < ApplicationRecord
  3. self.table_name = 'posts'
  4. end
  5. class PostTag < ApplicationRecord
  6. self.table_name = 'post_tags'
  7. end
  8. class PostVersion < ApplicationRecord
  9. self.table_name = 'post_versions'
  10. end
  11. def up
  12. create_table :post_versions do |t|
  13. t.references :post, null: false, foreign_key: true
  14. t.integer :version_no, null: false
  15. t.string :event_type, null: false
  16. t.string :title
  17. t.string :url, limit: 768, null: false
  18. t.string :thumbnail_base, limit: 2000
  19. t.text :tags, null: false
  20. t.references :parent, foreign_key: { to_table: :posts }
  21. t.datetime :original_created_from
  22. t.datetime :original_created_before
  23. t.datetime :created_at, null: false
  24. t.references :created_by_user, foreign_key: { to_table: :users }
  25. t.index [:post_id, :version_no], unique: true
  26. t.check_constraint 'version_no > 0'
  27. t.check_constraint "event_type IN ('create', 'update', 'discard', 'restore')"
  28. end
  29. say_with_time 'Backfilling post_versions' do
  30. Post.find_in_batches(batch_size: 500) do |posts|
  31. post_ids = posts.map(&:id)
  32. tag_names_by_post_id =
  33. PostTag
  34. .joins('INNER JOIN tags ON tags.id = post_tags.tag_id')
  35. .joins('INNER JOIN tag_names ON tag_names.id = tags.tag_name_id')
  36. .where(post_id: post_ids)
  37. .where('post_tags.discarded_at IS NULL')
  38. .where('tags.discarded_at IS NULL')
  39. .where('tag_names.discarded_at IS NULL')
  40. .pluck('post_tags.post_id', 'tag_names.name')
  41. .each_with_object(Hash.new { |h, k| h[k] = [] }) do |(post_id, tag_name), h|
  42. h[post_id] << tag_name
  43. end
  44. rows = posts.map do |post|
  45. tags = tag_names_by_post_id[post.id].uniq.sort.join(' ')
  46. { post_id: post.id,
  47. version_no: 1,
  48. event_type: 'create',
  49. title: post.title,
  50. url: post.url,
  51. thumbnail_base: post.thumbnail_base,
  52. tags:,
  53. parent_id: post.parent_id,
  54. original_created_from: post.original_created_from,
  55. original_created_before: post.original_created_before,
  56. created_at: post.created_at,
  57. created_by_user_id: post.uploaded_user_id }
  58. end
  59. PostVersion.insert_all!(rows) if rows.present?
  60. end
  61. end
  62. end
  63. def down
  64. drop_table :post_versions
  65. end
  66. end