Skip to content

Instantly share code, notes, and snippets.

@msimonborg
Last active July 18, 2017 08:34
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 msimonborg/907eb513fdde9ab48ee881d43ddb8378 to your computer and use it in GitHub Desktop.
Save msimonborg/907eb513fdde9ab48ee881d43ddb8378 to your computer and use it in GitHub Desktop.
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
source "https://rubygems.org"
# Activate the gem you are reporting the issue against.
gem "activerecord", "5.1.0"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
# 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 :comments, force: true do |t|
t.string :comment
t.string :ref_id
t.string :ref_type
end
create_table :books, force: true do |t|
t.string :title
end
create_table :articles, force: true do |t|
t.string :title
end
end
class Comment < ActiveRecord::Base
belongs_to :book, class_name: 'Book', foreign_key: 'ref_id'
belongs_to :article, class_name: 'Article', foreign_key: 'ref_id'
belongs_to :ref, polymorphic: true
def self.distinct_titles
comment_ids = ids
Article.titles_for_comments(comment_ids) + Book.titles_for_comments(comment_ids)
end
end
class Book < ActiveRecord::Base
has_many :comments, as: :ref
def self.titles_for_comments(comment_ids)
joins(:comments).where(comments: { id: comment_ids }).distinct.pluck(:title)
end
end
class Article < ActiveRecord::Base
has_many :comments, as: :ref
def self.titles_for_comments(comment_ids)
joins(:comments).where(comments: { id: comment_ids }).distinct.pluck(:title)
end
end
class BugTest < Minitest::Test
def test_association_stuff
book_one = Book.create! title: 'Book1'
book_two = Book.create! title: 'Book2'
book_three = Book.create! title: 'Book3'
article_one = Article.create! title: 'Article1'
article_two = Article.create! title: 'Article2'
book_one.comments << Comment.create!(comment: 'comment1')
book_one.comments << Comment.create!(comment: 'comment2')
article_one.comments << Comment.create!(comment: 'comment3')
book_three.comments << Comment.create!(comment: 'comment4')
[book_one, book_three, article_one].each(&:save)
assert_equal ['Article1'], Article.titles_for_comments(Comment.ids)
assert_equal %w[Book1 Book3], Book.titles_for_comments(Comment.ids)
assert_equal %w[Article1 Book1 Book3], Comment.distinct_titles.sort
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment