Skip to content

Instantly share code, notes, and snippets.

@iamvery
Last active February 17, 2017 14:55
Show Gist options
  • Save iamvery/d59f0d3fa0aaf58b326c1496a8b08058 to your computer and use it in GitHub Desktop.
Save iamvery/d59f0d3fa0aaf58b326c1496a8b08058 to your computer and use it in GitHub Desktop.

Demonstration of surprising association order dependency in activerecord

See it be weird:

$ bundle install
$ bundle exec ruby boom.rb
require "./foo"
f = Foo.create!
Bar.create!(foo_ids: [f.id])
require "active_record"
require "logger"
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Base.connection.create_table :foos do |t|
end
ActiveRecord::Base.connection.create_table :bars do |t|
end
ActiveRecord::Base.connection.create_table :foo_bars do |t|
t.belongs_to :foo, null: false
t.belongs_to :bar, null: false
end
class Foo < ActiveRecord::Base
has_many :bars, through: :foo_bars
has_many :foo_bars
end
class Bar < ActiveRecord::Base
has_many :foos, through: :foo_bars
has_many :foo_bars
end
class FooBar < ActiveRecord::Base
belongs_to :foo
belongs_to :bar
end
source "https://rubygems.org"
gem "activerecord"#, "4.2.7.1"
gem "sqlite3"
GEM
remote: https://rubygems.org/
specs:
activemodel (5.0.1)
activesupport (= 5.0.1)
activerecord (5.0.1)
activemodel (= 5.0.1)
activesupport (= 5.0.1)
arel (~> 7.0)
activesupport (5.0.1)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (~> 0.7)
minitest (~> 5.1)
tzinfo (~> 1.1)
arel (7.1.4)
concurrent-ruby (1.0.4)
i18n (0.8.0)
minitest (5.10.1)
sqlite3 (1.3.13)
thread_safe (0.3.5)
tzinfo (1.2.2)
thread_safe (~> 0.1)
PLATFORMS
ruby
DEPENDENCIES
activerecord
sqlite3
BUNDLED WITH
1.13.7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment