Skip to content

Instantly share code, notes, and snippets.

@benmoss
Last active December 15, 2015 20:00
Show Gist options
  • Save benmoss/5315831 to your computer and use it in GitHub Desktop.
Save benmoss/5315831 to your computer and use it in GitHub Desktop.
Nested has_many throughs with default scopes don't work as expected
unless File.exists?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'sqlite3'
GEMFILE
system 'bundle'
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 :topics do |t|
end
create_table :conversations do |t|
t.integer :topic_id
t.integer :parent_id
end
end
class Topic < ActiveRecord::Base
has_many :conversations
has_many :replies, through: :conversations
end
class Conversation < ActiveRecord::Base
belongs_to :topic
has_many :replies, foreign_key: "parent_id"
def self.default_scope
where(parent_id: nil)
end
end
class Reply < Conversation
belongs_to :parent, class_name: "Conversation"
def self.default_scope
where(arel_table[:parent_id].not_eq(nil))
end
end
class BugTest < MiniTest::Unit::TestCase
def test_association_stuff
topic = Topic.create
conversation = Conversation.create(topic: topic)
reply = Reply.create(parent: conversation, topic: topic)
assert_equal([reply], topic.replies)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment