Giter Club home page Giter Club logo

acts_as_tree's Introduction

ActsAsTree

CI Gem Version

ActsAsTree extends ActiveRecord to add simple support for organizing items into parent–children relationships. By default, ActsAsTree expects a foreign key column called parent_id.

Example

class Category < ActiveRecord::Base
  acts_as_tree order: "name"
end

root      = Category.create("name" => "root")
child1    = root.children.create("name" => "child1")
subchild1 = child1.children.create("name" => "subchild1")

root.parent   # => nil
child1.parent # => root
root.children # => [child1]
root.children.first.children.first # => subchild1

We also have a convenient TreeView module you can mixin if you want a little visual representation of the tree structure. Example:

class Category < ActiveRecord::Base
  extend ActsAsTree::TreeView

  acts_as_tree order: 'name'
end

> Category.tree_view(:name)
root
 |_ child1
 |    |_ subchild1
 |    |_ subchild2
 |_ child2
      |_ subchild3
      |_ subchild4
=> nil

And there's a TreeWalker module (traversing the tree using depth-first search (default) or breadth-first search) as well. Example given the Model Page as

class Page < ActiveRecord::Base
  extend ActsAsTree::TreeWalker

  acts_as_tree order: 'rank'
end

In your view you could traverse the tree using

<% Page.walk_tree do |page, level| %>
  <%= link_to "#{'-'*level}#{page.name}", page_path(page) %><br />
<% end %>

You also could use walk_tree as an instance method such as:

<% Page.first.walk_tree do |page, level| %>
  <%= link_to "#{'-'*level}#{page.name}", page_path(page) %><br />
<% end %>

Compatibility

We no longer support Ruby 1.8 or versions of Rails/ActiveRecord older than 3.0. If you're using a version of ActiveRecord older than 3.0 please use 0.1.1.

Moving forward we will do our best to support the latest versions of ActiveRecord and Ruby.

Change Log

The Change Log has moved to the releases page.

Note on Patches/Pull Requests

  1. Fork the project.
  2. Make your feature addition or bug fix.
  3. Add tests for it. This is important so we don't break it in a future version unintentionally.
  4. Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself so we can ignore when we pull)
  5. Send us a pull request. Bonus points for topic branches.
  6. All contributors to this project, after their first accepted patch, are given push access to the repository and are welcome as full contributors to ActsAsTree. All we ask is that all changes go through CI and a Pull Request before merging.

Releasing new versions

  1. We follow Semver. So if you're shipping interface breaking changes then bump the major version. We don't care if we ship version 1101.1.1, as long as people know that 1101.1.1 has breaking differences from 1100.0. If you're adding new features, but not changing existing functionality bump the minor version, if you're shipping a bugfix, just bump the patch.
  2. Following the above rules, change the version found in lib/acts_as_tree/version.rb.
  3. Commit these changes in one "release-prep" commit (on the master branch).
  4. Push that commit up to the repo.
  5. Run rake release This will create and push a tag to GitHub, then generate a gem and push it to Rubygems.
  6. Create a new release from the tag on GitHub, by choosing "Draft a new release" button on the releases tab and include the relevant changes in the description.
  7. Profit.

License (MIT)

Copyright (c) 2007 David Heinemeier Hansson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

acts_as_tree's People

Contributors

545ch4 avatar adamkleingit avatar agentydragon avatar akicho8 avatar alexmreis avatar amerine avatar dhh avatar donv avatar dv avatar edwardbetts avatar felixbuenemann avatar ioquatix avatar jeremy avatar kenn avatar klacointe avatar lukasztackowiak avatar makaroni4 avatar marshall-lee avatar mbenitezm avatar mischa78 avatar mishina2228 avatar rainchen avatar schlick avatar seanhussey avatar swanandp avatar two9a avatar xuanxu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

acts_as_tree's Issues

2.6's use of `level` clashes with my database column

I was wondering why updating to 2.6 broke my app
then I checked the diff and saw

v2.5.1...v2.6.0

+    def level
+      self.ancestors.size
+    end

my app already uses level to store the depth

CREATE TABLE regions (
    id integer NOT NULL,
    name character varying,
    level integer,
    parent_id integer,
);

any suggestion for how to avoid this name conflict?

Sinatra

Does acts_as_tree work with Sinatra ?
I am trying to get it working but havent been successful so far.

Avoid loading Database on acts_as_tree declaration

Right now when doing rake assets:precompile with no database
I get an exception:

PG::ConnectionBad: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
...
/usr/local/bundle/gems/activerecord-5.0.0.1/lib/active_record/attribute_methods/primary_key.rb:73:in `primary_key'
/usr/local/bundle/gems/acts_as_tree-2.5.0/lib/acts_as_tree.rb:68:in `acts_as_tree'

This was introduced in #52

And is caused by:

def acts_as_tree(options = {})
  configuration = {
    primary_key:   primary_key,
    ...
  }

  configuration.update(options) if options.is_a?(Hash)
  ...
end

Because that primary_key is always hit
I can't even override it.

Maybe

configuration = {}
configuration[:primary_key] = options[:primary_key] || primary_key
...

walk_tree_bfs doesn not implement BFS

the current implementation of walk_tree_bfs actually implements DFS, as evidenced by the fact that it is almost identical to walk_tree_dfs

in other words, walk_tree_bfs node {...} is identical to walk_tree_dfs node { |node,level| node.children.each { |child| ... }}, modulo some corner-cases

I think the tests used in test/acts_as_tree_test.rb are not deep enough to show the difference, but if you take

1
-2
--3
---4
-5
--6
---7

then the current implementation generate

1 2 5 3 4 6 7

while I believe true BFS would generate

1 2 5 3 6 4 7

(4 and 6 are switched)

a correct implementation should use a FIFO to keep tracks of the next generation; I will suggest one later, unless someone beats me to it or explains that I'm mistaken

order field is not wrapped in backquotes

My table has index field.

# model
class MenuItem < ApplicationRecord
  acts_as_tree order: :index
end
# console
>> MenuItem.roots
 MenuItem Load (0.3ms)  SELECT  `menu_items`.* FROM `menu_items` WHERE `menu_items`.`parent_id` IS NULL ORDER BY index
Traceback (most recent call last):
ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index' at line 1: SELECT  `menu_items`.* FROM `menu_items` WHERE `menu_items`.`parent_id` IS NULL ORDER BY index)

Solution is to backquote order field:

acts_as_tree order: "`index`"
# or
acts_as_tree order: "`#{table_name}`.`index`"

When I use that field manually it is correctly wrapped by rails:

scope :root_items, -> { where(parent: nil).order(:index) }
# resulting sql
SELECT  `menu_items`.* FROM `menu_items` WHERE `menu_items`.`parent_id` IS NULL ORDER BY `menu_items`.`index` ASC

NameError: uninitialized constant ActsAsTree::TreeView

I'm using Rails 5.1.3. When I test in Rails Console as follows I get error NameError: uninitialized constant ActsAsTree::TreeView.

$ bundle exec rails c
Running via Spring preloader in process 49432
Loading development environment (Rails 5.1.4)
irb(main):001:0> user1 = User.create(email: '[email protected]', password: '12345678', encrypted_password: '12345678')
   (0.2ms)  BEGIN
  User Exists (1.3ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "[email protected]"], ["LIMIT", 1]]
  SQL (1.2ms)  INSERT INTO "users" ("email", "encrypted_password", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["email", "[email protected]"], ["encrypted_password", "12345678"], ["created_at", "2017-11-05 14:18:21.095366"], ["updated_at", "2017-11-05 14:18:21.095366"]]
   (0.4ms)  COMMIT
=> #<User id: 1, email: "[email protected]", created_at: "2017-11-05 14:18:21", updated_at: "2017-11-05 14:18:21">
irb(main):002:0>   user1.profile = UserProfile.create(user_id: user1.id)
   (0.1ms)  BEGIN
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  SQL (1.1ms)  INSERT INTO "user_profiles" ("user_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["user_id", 1], ["created_at", "2017-11-05 14:18:27.586413"], ["updated_at", "2017-11-05 14:18:27.586413"]]
   (0.3ms)  COMMIT
  UserProfile Load (0.3ms)  SELECT  "user_profiles".* FROM "user_profiles" WHERE "user_profiles"."user_id" = $1 LIMIT $2  [["user_id", 1], ["LIMIT", 1]]
=> #<UserProfile id: 1, user_id: 1, created_at: "2017-11-05 14:18:27", updated_at: "2017-11-05 14:18:27">
irb(main):003:0> token1 = SkillToken.create(name: "eat", weight: 1, user_profile_id: u.profile.id)
NameError: uninitialized constant ActsAsTree::TreeView
	from app/models/skill_token.rb:6:in `<class:SkillToken>'
	from app/models/skill_token.rb:1:in `<top (required)>'
	from (irb):3
irb(main):004:0> require 'acts_as_tree'
=> true
irb(main):005:0> token1 = SkillToken.create(name: "eat", weight: 1, user_profile_id: u.profile.id)
NameError: uninitialized constant ActsAsTree::TreeView

I created the following models:

class SkillToken < ActiveRecord::Base
  belongs_to :profile, class_name: 'UserProfile'
  belongs_to :parent
  validates_presence_of :name

  extend ActsAsTree::TreeView
  acts_as_tree order: 'name'
end
class Parent < ApplicationRecord
  has_many :skill_tokens
end
class UserProfile < ApplicationRecord
  belongs_to :user
  has_many :skill_tokens
end
class ActsAsTree < ApplicationRecord
  belongs_to :parent_id
end
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :profile, class_name: 'UserProfile'
  # has_many :skill_tokens, :through => :profile
  delegate :skill_tokens, :to => :profile
end

I created the following relevant migrations and migrated them into PSQL with rails db:drop db:create db:migrate:

class CreateSkillTokens < ActiveRecord::Migration[5.1]
  def change
    create_table :skill_tokens do |t|
      t.string :name
      t.decimal :amount
      t.decimal :weight
      t.references :parent, foreign_key: true
      t.references :user_profile, foreign_key: true

      t.timestamps
    end
  end
end
class CreateParents < ActiveRecord::Migration[5.1]
  def change
    create_table :parents do |t|

      t.timestamps
    end
  end
end

uninitialized constant <model>::ActsAsTree

I added acts_as_tree to my Gemfile and did a bundle install but when I try to add the code

class FilingCategory < ActiveRecord::Base
    include ActsAsTree
    acts_as_tree order: 'name'
end

I get uninitialized constant FilingCategory::ActsAsTree what am I doing wrong?

v2.6 doesn't play nice with Enumerize gem anymore

I have this model:

class SuccessCriterion < ActiveRecord::Base
extend Enumerize
extend ActsAsTree::TreeWalker

enumerize :level, in: [:a, :aa, :aaa]

acts_as_tree order: :position, dependent: :restrict_with_error
acts_as_list scope: [:parent_id]
end


After upgrading from v2.5.1 to v2.6, I get this error when calling`success_criterion.level_text`:

    undefined method `text' for 0:Fixnum

Any idea where's the problem?

Fix rails 4.0 deprecations

DEPRECATION WARNING: The following options in your <model_name>.has_many :children declaration are deprecated: :order. Please use a scope block instead. For example, the following:

has_many :spam_comments, conditions: { spam: true }, class_name: 'Comment'

should be rewritten as the following:

has_many :spam_comments, -> { where spam: true }, class_name: 'Comment'

DEPRECATION WARNING: Calling #scope or #default_scope with a hash is deprecated. Please use a lambda containing a scope. E.g. scope :red, -> { where(color: 'red') }. (called from acts_as_tree at (eval):3)

How to generate full ul/li tree with walk_tree?

Sorry if this is the wrong place for this but how would you take this example:

<% Page.walk_tree do |page, level| %>
<%= link_to "#{'-'*level}#{page.name}", page_path(page) %>

<% end %>

And turn this into a

  • list with items? I am trying to use this with jstree to output the tree view.

counter_cache callbacks called twice

Gem version: 2.6.1
Rails version: 5.0.1

$ rails new treeapp
# add acts_as_tree to Gemfile and bundle
$ ./bin/rails g scaffold Node label parent_id:integer children_count:integer
$ ./bin/rails db:migrate

The Node class:

class Node < ApplicationRecord
  acts_as_tree counter_cache: true
end

Create the following structure using the browser ( a -> 1 ; a.1 -> 2; a.2 -> 3; b -> 4 ):

root
 |_ a
 |    |_ a.1
 |    |_ a.2
 |_ b

Then through the browser move a.2 under b, browse to /nodes/3/edit update the parent_id to 4 (b node) and submit the form. This is what I get in the log:

Started PATCH "/nodes/3" for ::1 at 2017-02-24 12:55:13 +0100
Processing by NodesController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"x9Rk", "node"=>{"label"=>"a.2", "parent_id"=>"4", "children_count"=>""}, "commit"=>"Update Node", "id"=>"3"}
  Node Load (0.1ms)  SELECT  "nodes".* FROM "nodes" WHERE "nodes"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]
   (0.1ms)  begin transaction
  SQL (0.5ms)  UPDATE "nodes" SET "parent_id" = ?, "updated_at" = ? WHERE "nodes"."id" = ?  [["parent_id", 4], ["updated_at", 2017-02-24 11:55:13 UTC], ["id", 3]]
  SQL (0.1ms)  UPDATE "nodes" SET "children_count" = COALESCE("children_count", 0) + 1 WHERE "nodes"."id" = ?  [["id", 4]]
  SQL (0.2ms)  UPDATE "nodes" SET "children_count" = COALESCE("children_count", 0) - 1 WHERE "nodes"."id" = ?  [["id", 1]]
  SQL (0.2ms)  UPDATE "nodes" SET "children_count" = COALESCE("children_count", 0) - 1 WHERE "nodes"."id" = ?  [["id", 1]]
  SQL (0.2ms)  UPDATE "nodes" SET "children_count" = COALESCE("children_count", 0) + 1 WHERE "nodes"."id" = ?  [["id", 4]]
   (2.5ms)  commit transaction
Redirected to http://localhost:3000/nodes/3
Completed 302 Found in 17ms (ActiveRecord: 3.9ms)

It seems like the counter_cache callbacks are being called twice. After this operation :children_count for a is now 0 and children count for b is now 2 when they should be 1 for a and 1 for b.

What am I missing? Thanks!

Can't Process Ordering on a column named as order

if you have a column named as order you can't process FaqLabel.walk_tree for acts_as_tree order: 'order'. I was getting errors like

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "order"
LINE 1: ...bels" WHERE "faq_labels"."parent_id" IS NULL  ORDER BY order
                                                                  ^
: SELECT "faq_labels".* FROM "faq_labels" WHERE "faq_labels"."parent_id" IS NULL  ORDER BY order

and I had to rename my column.

README include ActsAsTree redundant?

Is there a reason the README instruct's to include ActsAsTree into each ActiveRecord model, when it is already included into ActiveRecord::Base through the railtie?

Serialize tree structure as JSON

I'm building a very simple Category/Subcategory feature, and I would likely have used this gem had it some JSON serialization mechanism.

I don't have any great ideas on how to implement this, but I do think it'd make a good feature.

Cheers!

Question: walk_tree at the instance level

Hi, Please let me know if it possible to have walk_tree at the instance level instead of class?

Instead of

Organization.walk_tree

prefer

org = Organization.find(1234)
org.walk_tree

Create a recursive query in postgres

Is it possible to create recursive postgres queries to fetch the tree structure in one go?
i tried to google a bit around but didn't find much. if somebody could give me a starting point, that would be great

undefined method 'name' for nil:NilClass

I'm attempting to use acts_as_tree in a project, but when i call obj.children, i get the below stacktrace. When looking at the source, it appears to be breaking inside the below, delete_if block.

  def filter_binds(lhs_binds, removed_wheres)
    set = Set.new removed_wheres.map { |x| x.left.name }
    lhs_binds.dup.delete_if { |col,_| set.include? col.name }
  end
2.1.0 :009 > r.descendants
NoMethodError: undefined method `name' for nil:NilClass
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/relation/merger.rb:141:in `block in filter_binds'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/relation/merger.rb:141:in `delete_if'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/relation/merger.rb:141:in `filter_binds'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/relation/merger.rb:116:in `merge_multi_values'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/relation/merger.rb:72:in `merge'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/relation/spawn_methods.rb:44:in `merge!'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/association_scope.rb:99:in `block (2 levels) in add_constraints'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/association_scope.rb:94:in `each'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/association_scope.rb:94:in `block in add_constraints'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/association_scope.rb:44:in `each'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/association_scope.rb:44:in `each_with_index'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/association_scope.rb:44:in `add_constraints'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/association_scope.rb:19:in `scope'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/association.rb:103:in `association_scope'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/association.rb:87:in `scope'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/collection_association.rb:382:in `scope'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/collection_proxy.rb:37:in `initialize'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/relation/delegation.rb:78:in `new'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/collection_association.rb:37:in `reader'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/activerecord-4.0.2/lib/active_record/associations/builder/association.rb:70:in `children'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/acts_as_tree-1.5.0/lib/acts_as_tree.rb:155:in `descendants'
    from (irb):9
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/railties-4.0.2/lib/rails/commands/console.rb:90:in `start'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/railties-4.0.2/lib/rails/commands/console.rb:9:in `start'
    from /Users/ruckc/.rvm/gems/ruby-2.1.0/gems/railties-4.0.2/lib/rails/commands.rb:62:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'2.1.0 :010 > 

Specific order error

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'range' at line 1: SELECT `categories`.* FROM `categories`  WHERE `categories`.`parent_id` = 21  ORDER BY range

Category has a field range:integer, when I use the following code, error occurs.

acts_as_tree order: 'range'

It works if I use

acts_as_tree order: '`range`'

databaes: MySQL
acts_as_tree: 2.0.0
rails 4.1.1

Bug with `leaf?` method

leaf? method given me exception:

TypeError: nil can't be coerced into Fixnum
from /usr/local/bundle/gems/activerecord-5.0.0.1/lib/active_record/associations/collection_association.rb:319:in `+'

I have the same error with this:
model.association.children.size.zero?

Can we change implementation of leaf?


method from:

def leaf?
  children.size.zero?
end

to:

def leaf?
  children.blank?
end

?

Video: https://youtu.be/hutkAa39JcU

Gem Load Error is: uninitialized constant ActsAsTree::InstanceMethods::ActiveRecord

I am getting this error when using gem 'acts_as_tree' in my Rails project's Gemfile. (Rails 5.2.4, Ruby 2.5.0, on Ubuntu Linux), also when adding a , git: line to point to this repository.
Why is the gem assuming "ActiveRecord" is a local constant inside the module? Even ::ActiveRecord does not seem to help.
acts_as_tree worked fine when I was using Rails 4.2 and Ruby 1.9.3 before starting the upgrade.

$ bundle exec rails c
/usr/lib/ruby/vendor_ruby/bundler/runtime.rb:84:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'acts_as_tree'. (Bundler::GemRequireError)
Gem Load Error is: uninitialized constant ActsAsTree::InstanceMethods::ActiveRecord
Did you mean?  ActiveModel
Backtrace for gem load error is:
/home/jens/.bundle/ruby/2.5.0/acts_as_tree-2e2890a7c082/lib/acts_as_tree.rb:355:in `<module:InstanceMethods>'
/home/jens/.bundle/ruby/2.5.0/acts_as_tree-2e2890a7c082/lib/acts_as_tree.rb:242:in `<module:ActsAsTree>'
/home/jens/.bundle/ruby/2.5.0/acts_as_tree-2e2890a7c082/lib/acts_as_tree.rb:3:in `<top (required)>'
/usr/lib/ruby/vendor_ruby/bundler/runtime.rb:81:in `require'
/usr/lib/ruby/vendor_ruby/bundler/runtime.rb:81:in `block (2 levels) in require'
/usr/lib/ruby/vendor_ruby/bundler/runtime.rb:76:in `each'
/usr/lib/ruby/vendor_ruby/bundler/runtime.rb:76:in `block in require'
/usr/lib/ruby/vendor_ruby/bundler/runtime.rb:65:in `each'
/usr/lib/ruby/vendor_ruby/bundler/runtime.rb:65:in `require'
/usr/lib/ruby/vendor_ruby/bundler.rb:114:in `require'

Feature: walk_tree_to_children

I'd like to see something like this included next to TreeWalker::walk_tree:

module ActsAsTree::TreeWalker
    def self.prune
        throw :prune
    end

    def walk_tree_to_children(children, &block)
        marked = Set.new(children.collect(&:self_and_ancestors).flatten)

        walk_tree do |node, level|
            throw :prune unless marked.include?(node)

            yield node, level
        end
    end

    def walk_tree_dfs(where = {}, node = nil, level = 0, &block)
        nodes = (node.nil? ? roots : node.children).where(where)

        nodes.each do |child|
            catch(:prune) do
                yield(child, level)

                walk_tree_dfs(where, child, level + 1, &block)
            end
        end
    end
end

Method `collection_tree`?

The walk_tree method is very useful, but sometimes I don't need to walk the collection, I just want to have the collection itself, e.g. to pass it to a select input:

= f.association :success_criterion, collection: SuccessCriterion.collection_tree

I have created the following method in my SuccessCriterion model:

  def self.collection_tree
    success_criteria = []
    walk_tree do |success_criterion, level|
      success_criteria << success_criterion
    end
    success_criteria
  end

Maybe something like that exists already and I didn't find it?

Failing test with activerecord 5.2

After run the tests using activerecord 5.2 I got the failure below:

# Running:

...........................F..............................

Finished in 0.858197s, 67.5836 runs/s, 240.0381 assertions/s.

  1) Failure:
TreeTestWithCounterCache#test_update_parents_counter_cache [/<<PKGBUILDDIR>>/test/acts_as_tree_test.rb:501]:
Expected: 3
  Actual: 4

58 runs, 206 assertions, 1 failures, 0 errors, 0 skips

We are moving towards Rails 5 in Debian and this fix will be appreciated.

TreeWalker?

Release of a new gem for the TreeWalker? doc says it is there.. but Gem 2.0 is not including it yet.. So a new version would be awesome!

Presentation module clash

ActsAsTree is automatically included in https://github.com/amerine/acts_as_tree/blob/master/lib/acts_as_tree/railtie.rb:

ActiveSupport.on_load :active_record do
ActiveRecord::Base.send(:include, ActsAsTree)
end

However, ActsAsTree also includes a module Presentation. Unfortunately, if your rails app also has a model called Presentation, as mine does, this leads to problems due to the Presentation module overriding it, leading to errors like:
NoMethodError: undefined method `new' for ActsAsTree::Presentation:Module

Finding file location

hi
I wonder how to use the available methods to find the location of the file in a folder.
For building breadcrumbs, this is easy. We can do

<% if @current_folder %>
<div class="breadcrumbs">         
    <% if @current_folder #checking if we are under any folder %> 
        <%= link_to "Home", root_url %> 
        <% @current_folder.ancestors.reverse.each do |folder| %> 
            » <%= link_to folder.name, browse_path(folder) %> 
        <% end %> 
         »  <%= @current_folder.name %> 
    <%# else #if we are not under any folder%> 

    <% end %> 
</div>
<% end %>

but, what if i list all the files and want to show where they were created in a folder.
something like:
New File.txt =========== home/first
Second File.pdf ======== home/first/second

How to get this??

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.