Last active
January 13, 2016 07:25
-
-
Save flemse/fdd51ff5ad29a1f57134 to your computer and use it in GitHub Desktop.
Problems joining through polymorphic association with active record
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' | |
gem 'rails', github: 'rails/rails' | |
gem 'arel', github: 'rails/arel' | |
gem 'rack', github: 'rack/rack' | |
gem 'sprockets', github: 'rails/sprockets' | |
gem 'sprockets-rails', github: 'rails/sprockets-rails' | |
gem 'sass-rails', github: 'rails/sass-rails' | |
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 :posts, force: true do |t| | |
t.string :title | |
end | |
create_table :post_artifacts, force: true do |t| | |
t.references :post | |
t.integer :rule | |
t.references :artifact, polymorphic: true | |
end | |
create_table :comments, force: true do |t| | |
t.text :content | |
end | |
end | |
class Post < ActiveRecord::Base | |
has_many :post_artifacts | |
has_many :comments, through: :post_artifacts, source: :artifact, source_type: 'Comment' | |
has_many :a_comments, -> { PostArtifact.a }, through: :post_artifacts, source: :artifact, source_type: 'Comment' | |
end | |
class Comment < ActiveRecord::Base | |
has_many :post_artifacts, as: :artifact | |
has_many :a_posts, -> { PostArtifact.a }, through: :post_artifacts, source: :post | |
end | |
class PostArtifact < ActiveRecord::Base | |
enum rule: [:a, :b] | |
belongs_to :post | |
belongs_to :artifact, polymorphic: true | |
end | |
class BugTest < Minitest::Test | |
def test_association_stuff | |
post = Post.create! | |
10.times { | |
post.a_comments << Comment.create! | |
} | |
assert_equal 10, Post.includes(:comments).flat_map(&:comments).count #working | |
assert_equal 10, Post.includes(:a_comments).flat_map(&:a_comments).count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment