Skip to content

Instantly share code, notes, and snippets.

@iantropov
Created September 28, 2013 13:43
Show Gist options
  • Save iantropov/6742197 to your computer and use it in GitHub Desktop.
Save iantropov/6742197 to your computer and use it in GitHub Desktop.
Foreign key violation, caused by incorrect order of destroying linked objects (link is 'belongs_to')
gem 'activerecord', '4.0.0'
require 'active_record'
require 'minitest/autorun'
require 'logger'
gem "schema_plus"
require 'schema_plus'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: 'localhost',
port: '5432',
username: 'postgres',
password: '123123',
database: 'dev',
schema_search_path: 'public',
encoding: 'utf8',
template: 'template1'
)
ActiveRecord::Base.logger = Logger.new(STDOUT)
class ActiveRecord::Schema
include ::SchemaPlus::ActiveRecord::ConnectionAdapters
end
ActiveRecord::Schema.define do
drop_table :comments, if_exists: true
drop_table :posts , if_exists: true
create_table :posts do |t|
end
create_table :comments do |t|
t.integer :post_id
end
add_foreign_key :comments, :post_id, :posts, :id
end
class Post < ActiveRecord::Base
end
class Comment < ActiveRecord::Base
belongs_to :post, :dependent => :destroy
end
class BugTest < MiniTest::Unit::TestCase
def test_association_stuff
post = Post.create!
comment = Comment.new
comment.post = post
comment.save!
comment.destroy!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment