Skip to content

Instantly share code, notes, and snippets.

@BookOfGreg
Last active February 17, 2017 14:52
Show Gist options
  • Save BookOfGreg/64b1e19410cb657280d35d4d374493c7 to your computer and use it in GitHub Desktop.
Save BookOfGreg/64b1e19410cb657280d35d4d374493c7 to your computer and use it in GitHub Desktop.
Migrations and test code for reverse polymorphic association.
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', '~> 5.0.1'
gem 'sqlite3'
GEMFILE
system 'bundle install'
end
require 'bundler'
Bundler.setup(:default)
require 'minitest/autorun'
require 'active_record'
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 :versions do |t|
end
create_table :articles do |t|
end
create_table :pages do |t|
end
create_table :contents do |t|
t.integer "page_id", null: false
t.integer "content_id"
t.string "content_type"
end
end
class Page < ActiveRecord::Base
has_many :contents
has_many :articles, through: :contents, source: :content, source_type: "Article"
has_many :versions, through: :contents, source: :content, source_type: "Version"
end
class Content < ActiveRecord::Base
belongs_to :page
belongs_to :content, polymorphic: true
end
class Article < ActiveRecord::Base
has_one :content, as: :content
has_one :page, through: :content
end
class Version < ActiveRecord::Base
has_one :content, as: :content
has_one :page, through: :content
end
class BugTest < Minitest::Test
def test_polymorphic_join_conditions
page = Page.create
page.versions.create
page.articles.create
page.reload
assert_equal 1, page.versions.count
assert_equal page.versions.first, Version.last
assert_equal 1, page.articles.count
assert_equal page.articles.first, Article.last
assert_equal 2, page.contents.count
assert_equal Version.last.page, page
assert_equal Article.last.page, page
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment