Skip to content

Instantly share code, notes, and snippets.

@zachwalton
Created October 5, 2017 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachwalton/76f08d0e206f7c61f5c5c0c907a1e307 to your computer and use it in GitHub Desktop.
Save zachwalton/76f08d0e206f7c61f5c5c0c907a1e307 to your computer and use it in GitHub Desktop.
has_and_belongs_to_many association bug
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
source "https://rubygems.org"
gem "rails", "5.1.3"
gem "arel"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# 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 |t|
t.integer :comment_id
end
create_table :comments, force: true do |t|
t.integer :post_id
end
create_table :comments_posts, force: true do |t|
t.integer :comment_id
t.integer :post_id
end
end
class Post < ActiveRecord::Base
has_and_belongs_to_many :comments
def add_comment(reload:)
comments << Comment.new
comments.reload if reload
end
end
class Comment < ActiveRecord::Base
has_and_belongs_to_many :posts
belongs_to :post
end
class BugTest < Minitest::Test
def test_association_stuff
# Reloading the association before the Post is saved breaks
# the association
post = Post.new
post.add_comment(reload: true)
post.save
assert_equal 1, post.comments.count
assert_nil post.comments.first
# Not reloading the association before the Post is saved
# works as expected
post = Post.new
post.add_comment(reload: false)
post.save
assert_equal 1, post.comments.count
assert_kind_of Comment, post.comments.first
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment