Skip to content

Instantly share code, notes, and snippets.

@skorfmann
Last active December 25, 2015 01:59
Show Gist options
  • Select an option

  • Save skorfmann/6898802 to your computer and use it in GitHub Desktop.

Select an option

Save skorfmann/6898802 to your computer and use it in GitHub Desktop.
Subsequent calls of AwesomeActor#accounts or AwesomeActor#clients are failing
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'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :actors do |t|
t.string :name
t.string :type
t.timestamps
end
create_table :roles do |t|
t.belongs_to :actor
t.belongs_to :entity
t.timestamps
end
create_table :entities do |t|
t.string :name
t.belongs_to :subject, polymorphic: true
t.timestamps
end
create_table :accounts do |t|
t.string :name
t.timestamps
end
create_table :clients do |t|
t.string :name
t.timestamps
end
end
class Account < ActiveRecord::Base
has_one :entity, as: :subject
end
class Client < ActiveRecord::Base
has_one :entity, as: :subject
end
class Entity < ActiveRecord::Base
belongs_to :subject, polymorphic: true
has_many :roles
has_many :actors, through: :roles
end
class Role < ActiveRecord::Base
belongs_to :actor
belongs_to :entity
end
class Actor < ActiveRecord::Base
has_many :roles
has_many :entities, through: :roles
end
class AwesomeActor < Actor
has_many :accounts, through: :entities, source: :subject, source_type: 'Account'
has_many :clients, through: :entities, source: :subject, source_type: 'Client'
end
class HasManyThroughWithPolymorphicSourceTest < Minitest::Test
def setup
@account = Account.create!
@client = Client.create!
@awesome_actor = AwesomeActor.create!
@account_entity = Entity.create!(subject: @account)
@client_entity = Entity.create!(subject: @client)
Role.create!(actor: @awesome_actor, entity: @account_entity)
Role.create!(actor: @awesome_actor, entity: @client_entity)
end
#green when run in isolation
def test_awesome_actor_account_association
assert_equal [@account], @awesome_actor.accounts
end
#green when run in isolation
def test_awesome_actor_client_association
assert_equal [@client], @awesome_actor.clients
end
def test_awesome_actor_entities_association
@awesome_actor.clients
assert_equal [@account_entity, @client_entity], @awesome_actor.entities
end
def test_awesome_actor_subsequent_calls_to_associations
@awesome_actor.accounts
assert_equal [@client], @awesome_actor.clients
end
def test_awesome_actor_subsequent_calls_to_associations_reversed
@awesome_actor.clients
assert_equal [@account], @awesome_actor.accounts
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment