Skip to content

Instantly share code, notes, and snippets.

@composerinteralia
Created October 28, 2022 20:12
Show Gist options
  • Save composerinteralia/cb90284a66b72ba53575354860d74aa1 to your computer and use it in GitHub Desktop.
Save composerinteralia/cb90284a66b72ba53575354860d74aa1 to your computer and use it in GitHub Desktop.
Autosave validations
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Activate the gem you are reporting the issue against.
gem "activerecord", "~> 7.0.0"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :users, force: true do |t|
end
create_table :emails, force: true do |t|
t.integer :user_id
end
create_table :roles, force: true do |t|
t.integer :email_id
end
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
validate :validation
def validation
$validations[self.class] += 1
end
end
class User < ApplicationRecord
has_many :emails
end
class Email < ApplicationRecord
belongs_to :user
has_many :roles
end
class Role < ApplicationRecord
belongs_to :email
end
class BugTest < Minitest::Test
def test_manual_save
$validations = Hash.new(0)
user = User.new
email = Email.new(user: user)
role = Role.new(email: email)
user.save!
email.save!
role.save!
assert_equal 1, $validations[Role]
assert_equal 1, $validations[Email]
assert_equal 1, $validations[User]
end
def test_autosave
$validations = Hash.new(0)
user = User.new
email = user.emails.build
email.roles.build
user.save!
assert_equal 3, $validations[Role]
assert_equal 2, $validations[Email]
assert_equal 1, $validations[User]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment