Last active
April 23, 2024 07:49
-
-
Save pioz/54bf843fa8a6e38f30f549835f95a63a to your computer and use it in GitHub Desktop.
Tenants
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'activerecord' | |
gem 'mysql2' | |
end | |
require 'active_record' | |
ActiveRecord::Base.establish_connection( | |
adapter: 'mysql', | |
host: 'localhost', | |
username: 'root', | |
database: 'tenants' | |
) | |
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
end | |
class Apartment < ApplicationRecord | |
has_many :properties | |
has_many :tenants, through: :properties | |
end | |
class Tenant < ApplicationRecord | |
has_many :properties | |
has_many :apartments, through: :properties | |
end | |
class Property < ApplicationRecord | |
belongs_to :apartment | |
belongs_to :tenant | |
end | |
def migrate | |
ActiveRecord::Schema.define do | |
create_table(:apartments) do |t| | |
t.string :unit_number, null: false | |
end | |
create_table(:tenants) do |t| | |
t.string :name, null: false | |
end | |
create_table(:properties) do |t| | |
t.references :apartment, null: false, foreign_key: true | |
t.references :tenant, null: false, foreign_key: true | |
end | |
end | |
end | |
migrate | |
puts 'Create Apartments' | |
apartment_records = 1_000_000.times.map do |i| | |
{ unit_number: "apartment_#{i}" } | |
end | |
Apartment.insert_all(apartment_records) | |
puts 'Create Tenants' | |
tenant_records = 1_000_000.times.map do |i| | |
{ name: "tenant_#{i}" } | |
end | |
Tenant.insert_all(tenant_records) | |
puts 'Create Properties' | |
apartment_ids = Apartment.pluck(:id) | |
tenant_ids = Tenant.pluck(:id) | |
property_records = tenant_ids.flat_map do |tenant_id| | |
rand(4).times.map do |i| | |
{ tenant_id: tenant_id, apartment_id: apartment_ids.sample } | |
end | |
end | |
property_records.each_slice(1000) do |slice| | |
Property.insert_all(slice) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment