Skip to content

Instantly share code, notes, and snippets.

@scottmatthewman
Last active August 29, 2015 14:19
Show Gist options
  • Save scottmatthewman/3b01023e58ae908510e8 to your computer and use it in GitHub Desktop.
Save scottmatthewman/3b01023e58ae908510e8 to your computer and use it in GitHub Desktop.
Rails: has_many :through does not autosave when the parent is new
gem 'activerecord', '4.2.1'
require 'active_record'
require 'minitest/autorun'
require 'logger'
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
# 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 :posts, force: true do |_|
end
create_table :catalog_memberships, force: true do |t|
t.integer :post_id
t.integer :catalog_id
end
create_table :catalogs, force: true do |t|
t.string :title
end
end
class Post < ActiveRecord::Base
has_many :catalog_memberships, inverse_of: :post
has_many :catalogs, through: :catalog_memberships, inverse_of: :posts, autosave: true
end
class CatalogMembership < ActiveRecord::Base
belongs_to :post, inverse_of: :catalog_memberships
belongs_to :catalog, inverse_of: :catalog_memberships
end
class Catalog < ActiveRecord::Base
has_many :catalog_memberships, inverse_of: :catalog
has_many :posts, through: :catalog_memberships, inverse_of: :catalogs, autosave: true
end
class BugTest < Minitest::Test
# This test passes
def test_autosave_has_many_through_on_existing_parent
catalog = Catalog.create!(title: 'Original Title')
catalog.title = 'Amended Title'
post = Post.create!
post.catalogs = [catalog]
post.save!
assert_equal 1, post.catalogs.count
assert_equal 'Amended Title', catalog.reload.title
end
# This test should also pass, but is instead failing
def test_autosave_has_many_through_on_new_parent
catalog = Catalog.create!(title: 'Original Title')
catalog.title = 'Amended Title'
post = Post.new
post.catalogs = [catalog]
post.save!
assert_equal 1, post.catalogs.count
assert_equal 'Amended Title', catalog.reload.title
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment