Created
April 8, 2015 16:28
-
-
Save dsimard/aca75b6c7e3dc2d31646 to your computer and use it in GitHub Desktop.
`has_many :through` an association that uses `includes` throws an error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Activate the gem you are reporting the issue against. | |
gem 'activerecord', '4.1.1' # as well as '4.2.0' | |
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 :people, force: true do |t| | |
t.string :name | |
end | |
create_table :relationships, force: true do |t| | |
t.integer :person_id | |
t.integer :other_id | |
t.integer :relationship_type_id | |
end | |
create_table :relationship_types, force: true do |t| | |
t.integer :kind | |
end | |
end | |
class RelationshipType < ActiveRecord::Base | |
belongs_to :relationship | |
enum kind:[:friend, :family] | |
end | |
class Person < ActiveRecord::Base | |
has_many :relationships | |
has_many :family_relationships, ->{ family }, class_name: "Relationship" | |
has_many :types, through: :family_relationships, source: :relationship_type | |
has_many :family_members, through: :family_relationships, source: :person | |
end | |
class Relationship < ActiveRecord::Base | |
belongs_to :relationship_type | |
belongs_to :person | |
belongs_to :other, class_name: "Person", foreign_key: :other_id | |
scope :family, ->{ | |
includes(:relationship_type).where(relationship_types: { kind: RelationshipType.kinds[:family] }) | |
} | |
end | |
class BugTest < Minitest::Test | |
def test_has_many_through_includes | |
mike = Person.create! name: "Mike" | |
carly = Person.create! name: "Carly" | |
# Mike has Carly as a family member | |
family_type = RelationshipType.create! kind: RelationshipType.kinds[:family] | |
relationship = mike.relationships.create! other: carly, relationship_type: family_type | |
# Can find the family relationship | |
assert_equal 1, Relationship.family.count | |
assert_equal 1, mike.family_relationships.count | |
# Should find Carly has a family member but throws an error | |
assert_equal carly, mike.family_members.first | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment