Skip to content

Instantly share code, notes, and snippets.

@mh-mobile
Last active April 19, 2020 14:37
Show Gist options
  • Save mh-mobile/579c90a78d2c6d24c3007b70a801431f to your computer and use it in GitHub Desktop.
Save mh-mobile/579c90a78d2c6d24c3007b70a801431f to your computer and use it in GitHub Desktop.
has _one :through polymorphic association
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Activate the gem you are reporting the issue against.
gem "activerecord", "6.0.0"
gem "sqlite3"
end
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 :authors, force: true do |t|
end
create_table :hardbacks, force: true do |t|
end
create_table :paperbacks, force: true do |t|
end
create_table :books, force: true do |t|
t.string :author_id
t.string :format_type
t.integer :format_id
end
create_table :dust_jackets, force: true do |t|
t.string :hardback_id
end
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class Author < ApplicationRecord
has_one :book
has_one :hardback, through: :book, source: :format, source_type: "Hardback"
has_one :dust_jacket, through: :hardback
end
class Book < ApplicationRecord
#has_one :format, polymorphic: true
belongs_to :format, polymorphic: true
end
class Paperback < ApplicationRecord; end
class Hardback < ApplicationRecord
has_one :dust_jacket
end
class DustJacket < ApplicationRecord; end
class AuthorTest < Minitest::Test
def test_association
author = Author.create!
dust_jacket = DustJacket.new
hardback = Hardback.create!
hardback.dust_jacket = dust_jacket
book = Book.new
book.format = hardback
book.author_id = author.id
book.save!
author.reload
assert_equal dust_jacket, author.dust_jacket
end
end
Finished in 0.029099s, 34.3660 runs/s, 34.3660 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment