Skip to content

Instantly share code, notes, and snippets.

@harshalbhakta
Created July 31, 2019 06:08
Show Gist options
  • Save harshalbhakta/1c46ef0c591d39c9ee489eac460fe337 to your computer and use it in GitHub Desktop.
Save harshalbhakta/1c46ef0c591d39c9ee489eac460fe337 to your computer and use it in GitHub Desktop.
Awesome Nested Set after_create Bug
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem 'activerecord', '6.0.0.rc1'
gem 'sqlite3', '1.4.1'
gem 'awesome_nested_set', github: 'collectiveidea/awesome_nested_set', branch: 'master', require: false
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 :categories do |t|
t.string :name
t.string :slug
t.integer :parent_id, :null => true, :index => true
t.integer :lft, :null => false, :index => true
t.integer :rgt, :null => false, :index => true
# optional fields
t.integer :depth, :null => false, :default => 0
t.integer :children_count, :null => false, :default => 0
end
end
class Category < ActiveRecord::Base
acts_as_nested_set
# Won't work
after_create :update_slug
# Will work
# after_create_commit :update_slug
def update_slug
self.update! slug: self.name.parameterize
end
end
class BugTest < Minitest::Test
def test_association_stuff
# Create root categories
maths = Category.create! name: "Maths"
# Create Testing as root.
class_1 = Category.create! name: "Class 1", parent_id: maths.id
assert_equal 1, class_1.depth
assert_equal 1, class_1.ancestors.count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment