Skip to content

Instantly share code, notes, and snippets.

@samwgoldman
Last active December 18, 2015 13:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samwgoldman/5789657 to your computer and use it in GitHub Desktop.
Save samwgoldman/5789657 to your computer and use it in GitHub Desktop.
require "active_record" # 4.0.0.rc2
require "minitest/autorun"
class Migrate < ActiveRecord::Migration
self.verbose = false
def up
create_table(:profiles)
create_table(:networks)
create_table(:memberships) do |t|
t.references :network, null: false
t.references :profile, null: false
end
end
end
class Profile < ActiveRecord::Base
has_many :memberships
has_many :networks, through: :memberships
def shared_memberships(profile)
memberships.shared(profile)
end
end
class Network < ActiveRecord::Base
end
class Membership < ActiveRecord::Base
belongs_to :profile
belongs_to :network
def self.shared(other_profile)
# seems to be loading other_profile's memberships association using self.membership's scope
where(:network_id => other_profile.networks).map(&:network)
end
end
class TestSharedMemberships < MiniTest::Unit::TestCase
def setup
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
Migrate.new.up
@n = Network.create!
@p1 = Profile.create!
@p2 = Profile.create!
end
def test_share_profiles_with_network
Membership.create!(profile: @p1, network: @n)
Membership.create!(profile: @p2, network: @n)
# passes
assert_equal [@n], @p1.shared_memberships(@p2)
end
def test_share_profiles_with_network_2
Membership.create!(profile: @p1, network: @n)
# fails
assert_equal [], @p1.shared_memberships(@p2)
end
def test_share_profiles_with_network_3
Membership.create!(profile: @p1, network: @n)
# pre-load association outside of p1->memberships scope
@p2.networks
# passes
assert_equal [], @p1.shared_memberships(@p2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment