Skip to content

Instantly share code, notes, and snippets.

@vokshirg
Created December 11, 2023 17:51
Show Gist options
  • Save vokshirg/00407b985baa2a119a68013e98e19d39 to your computer and use it in GitHub Desktop.
Save vokshirg/00407b985baa2a119a68013e98e19d39 to your computer and use it in GitHub Desktop.
Migration example with stubbed models
class MergePaypalVerificationAndContacts < ActiveRecord::Migration[7.0]
class User < ApplicationRecord
self.table_name = :users
has_many :user_verifications, class_name: 'UserVerification'
has_one :paypal_verification, class_name: 'OldPaypalVerification'
end
class UserVerification < ApplicationRecord
self.table_name = :user_verifications
self.inheritance_column = :_type_disabled
belongs_to :user, inverse_of: :user_verifications
belongs_to :contact, inverse_of: :user_verification
enum _prefix: true, type: { personal: 0, corporate: 1, paypal: 2 }
end
class OldPaypalVerification < ApplicationRecord
self.table_name = :paypal_verifications
belongs_to :user
belongs_to :country
end
class Contact < ApplicationRecord
self.table_name = :contacts
has_one :user_verification, class_name: 'UserVerification'
belongs_to :country
belongs_to :entity, polymorphic: true
end
class NewPaypalVerification < Contact
self.table_name = :contacts
self.inheritance_column = :_type_disabled
default_scope { where(paypal: true) }
enum account_type: { personal: 0, corporate: 1 }
validates :account, :country, :address, :entity, :user, presence: true
validates :entity_id, uniqueness: { scope: %i[entity_type], conditions: -> { where(paypal: true) } }
alias_attribute :user, :entity
alias_attribute :account, :email
alias_attribute :account_type, :type
alias_attribute :user_id, :entity_id
end
def up
add_column :contacts, :verified, :boolean, default: :false
add_column :contacts, :paypal, :boolean, default: :false
Contact.reset_column_information
NewPaypalVerification.reset_column_information
# Итерируем PaypalVerification
# переносим в Contact данные
# обновляем Все связанные UserVerification привязывая верификацию к конкретному контакту
OldPaypalVerification.find_each do |pv|
params = pv.attributes.merge(entity_type: 'User', paypal: true).except!('id')
contact = NewPaypalVerification.create!(params)
uv_paypal = pv.user.user_verifications.type_paypal.first
uv_paypal.update(contact: contact) if uv_paypal
end
end
def down
raise 'Not Implemented'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment