Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save PragmaticEd/9120b843c7744aa60df869aaff1d4ba2 to your computer and use it in GitHub Desktop.
Save PragmaticEd/9120b843c7744aa60df869aaff1d4ba2 to your computer and use it in GitHub Desktop.
Illustrates the issue described in [#9517](https://github.com/rails/rails/issues/9517).
unless File.exists?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
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 :groups do |t|
end
create_table :events do |t|
t.references :group
t.references :user
t.datetime :starts_at
end
create_table :users do |t|
end
end
class Group < ActiveRecord::Base
has_many :events, -> { includes(:user) }
has_many :users, -> { uniq }, through: :events
end
class Event < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
class User < ActiveRecord::Base
has_many :events, -> { includes(:group) }
has_many :groups, through: :events
end
class BugTest < Minitest::Test
def test_association_stuff
group = Group.create!
user = User.create!
group.events << Event.create!(starts_at: DateTime.current, user_id: user.id)
assert_equal 1, group.users.count
assert_equal 1, Event.count
assert_equal group.id, Event.first.group.id
assert_equal 1, user.groups.count
assert_equal user.id, Event.first.user.id
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment