with_model icon indicating copy to clipboard operation
with_model copied to clipboard

Record creation fails when one with_model has a foreign key pointing to another with_model

Open dhnaranjo opened this issue 2 years ago • 0 comments

I made you a lil repro script. The child without foreign key is created just fine, the child with foreign key hits an exception.

require "bundler/inline"

gemfile do
  source "https://rubygems.org"
  gem "sqlite3"
  gem "combustion"
  gem "with_model"
  gem "minitest"
end

require "combustion"
require "minitest/autorun"
require "with_model"

# A hack to override some Combustion behavior
module Bundler
  def self.require(*)
    # noop
  end
end
ENV['DATABASE_URL'] = "sqlite3::memory:"
ENV['RAILS_ENV'] = "test"
Combustion.initialize! :active_record, database_reset: false, load_schema: false do
  config.enable_reloading = true
end

WithModel.runner = :minitest

class ForeignKeysSpec < Minitest::Spec
  extend WithModel

  with_model :Parent do
    model do
      has_many :children
      has_many :children_with_foreign_key, class_name: "ChildWithForeignKey"
    end
  end

  with_model :Child do
    table do |t|
      t.references :parent
    end

    model do
      belongs_to :parent
    end
  end

  with_model :ChildWithForeignKey do
    table do |t|
      t.references :parent, foreign_key: true
    end

    model do
      belongs_to :parent
    end
  end

  it "creates a child without a foreign key" do
    parent = Parent.create!
    child = parent.children.create!
    assert_equal parent, child.parent
  end

  it "creates a child with a foreign key" do
    parent = Parent.create!
    assert_raises ActiveRecord::StatementInvalid do
      parent.children_with_foreign_key.create!
    end
  end
end

dhnaranjo avatar Dec 21 '23 23:12 dhnaranjo