Skip to content

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

@dhnaranjo

Description

@dhnaranjo

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions