collectiveidea / awesome_nested_set

An awesome replacement for acts_as_nested_set and better_nested_set.
MIT License
2.39k stars 492 forks source link

Root returns the wrong result for scoped sets #436

Closed p8 closed 3 years ago

p8 commented 3 years ago

In the unreleased version root seems to ignore scoping and can return a result with the incorrect scope.

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', '~> 6.0'
  gem 'sqlite3'
  gem 'byebug'
  gem 'awesome_nested_set', require: false, git: 'git@github.com:collectiveidea/awesome_nested_set.git', ref: '6a2ed0fc6'
end

require 'active_record'
require 'minitest/autorun'
require 'logger'
require 'awesome_nested_set'

# 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 :users do |t|
    t.string :name
    t.timestamps
  end

  create_table :categories do |t|
    t.belongs_to :user
    t.integer :parent_id, :null => true, :index => true
    t.integer :lft, :null => false, :index => true
    t.integer :rgt, :null => false, :index => true
    t.string :name
    t.timestamps
  end
end

class User < ActiveRecord::Base
  has_many :categories
end

class Category < ActiveRecord::Base
  belongs_to :user
  acts_as_nested_set scope: :user
end

class BugTest < Minitest::Test
  def test_roots_are_scoped
    bob = User.create!(name: 'Bob')
    root = bob.categories.create(name: 'Category 1')
    alice = User.create!(name: 'Alice')

    # Alice has no categories so root should return nil
    assert_equal(nil, alice.categories.root)

    # On master (6a2ed0fc6) root returns the root for bob
    # assert_equal(root, alice.categories.root)
  end
end