Skip to content

Instantly share code, notes, and snippets.

@sergiocampama
Last active August 29, 2015 13:56
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 sergiocampama/8824843 to your computer and use it in GitHub Desktop.
Save sergiocampama/8824843 to your computer and use it in GitHub Desktop.
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'arel', github: 'rails/arel'
gem 'sqlite3'
GEMFILE
system 'bundle install'
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 :centers do |t|
end
create_table :lefts do |t|
end
create_table :rights do |t|
end
create_table :links do |t|
t.integer :center_id
t.integer :linkable_id
t.string :linkable_type
end
end
class Center < ActiveRecord::Base
has_many :links
has_many :left_links, -> { where(linkable_type: "Left") }, class_name: "Link"
has_many :lefts, through: :left_links, source: :linkable, source_type: "Left"
has_many :right_links, -> { where(linkable_type: "Right") }, class_name: "Link"
has_many :rights, through: :right_links, source: :linkable, source_type: "Right"
scope :with_right, -> (right) {
joins(:rights).where(rights: {id: right.id})
}
scope :with_left, -> (left) {
joins(:lefts).where(lefts: {id: left.id})
}
scope :with_left_and_right, -> (left, right) {
joins(:lefts).joins(:rights).where(lefts: {id: left.id}, rights: {id: right.id})
}
end
class Left < ActiveRecord::Base
has_many :links, -> { where(linkable_type: "Left") }, as: :linkable
has_many :centers, through: :links
end
class Right < ActiveRecord::Base
has_many :links, -> { where(linkable_type: "Right") }, as: :linkable
has_many :centers, through: :links
end
class Link < ActiveRecord::Base
belongs_to :center
belongs_to :linkable, polymorphic: true
end
class BugTest < Minitest::Test
def test_polymorphic_join
center = Center.create
left = Left.create
right = Right.create
center.lefts << left
center.rights << right
assert_equal 1, center.rights.count
assert_equal 1, center.lefts.count
assert_equal 1, left.centers.with_right(right).count #Fails
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment