Skip to content

Instantly share code, notes, and snippets.

@4ndv
Created November 15, 2023 14:21
Show Gist options
  • Save 4ndv/5edf42820907d9882dcb1727e662a3d3 to your computer and use it in GitHub Desktop.
Save 4ndv/5edf42820907d9882dcb1727e662a3d3 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "activerecord", "= 7.1.2"
gem "pg"
end
require "active_record"
require "logger"
ActiveRecord::Base.establish_connection(
adapter: "postgresql",
database: "callback_order_test",
encoding: "unicode",
host: "localhost",
port: "5432",
password: "postgres",
username: "postgres"
)
ActiveRecord::Schema.define do
drop_table "employees" if table_exists?("employees")
drop_table "projects" if table_exists?("projects")
drop_table "projects_employees" if table_exists?("projects_employees")
create_table "employees" do |t|
t.string "name"
t.timestamps
end
create_table "projects" do |t|
t.string "title"
t.timestamps
end
create_table "projects_employees" do |t|
t.references :employee
t.references :project
end
end
# Init logs after db is created
ActiveRecord::Base.logger = Logger.new(STDOUT)
class ProjectsEmployee < ActiveRecord::Base
belongs_to :project
belongs_to :employee
after_save do
puts "ProjectsEmployee after_save #{project.title} #{employee.name}"
end
after_commit do
puts "ProjectsEmployee after_commit #{project.title} #{employee.name}"
end
end
class Employee < ActiveRecord::Base
has_many :projects_employees
has_many :projects, through: :projects_employees
after_save do
puts "Employee after_save #{name}"
end
after_commit do
puts "Employee after_commit #{name}"
end
end
class Project < ActiveRecord::Base
has_many :projects_employees
has_many :employees, through: :projects_employees
after_save do
puts "Project after_save #{title}"
end
after_commit do
puts "Project after_commit #{title}"
end
end
puts "Creating Project"
Project.create(
employees: [
Employee.new(name: "A"),
Employee.new(name: "B")
],
title: "P1"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment