Today I would like to show how easy it can be to setup a tree structure with activescaffold.

At the end of this post we should have a tree structure in which we can CRUD elements, even changing the parent of a child.
In addition we can sort children of a parent by drag and drop.

As usual we will need my little how-to application.

1. Create a new menu model

rails g active_scaffold Menu name:string action:string position:integer ancestry:string
rake db:migrate

position attribute is needed for sorting and ancestry attribute for ancestry plugin.

2. Install plugins

rails plugin install git://github.com/rails/acts_as_list.git 
rails plugin install git://github.com/vhochstein/active_scaffold_sortable.git 
rails plugin install git://github.com/stefankroes/ancestry.git 

3. Include ancestry into Menu Model

app/model/menu.rb

class Menu < ActiveRecord::Base
  has_ancestry
end

4. Configure Menu Controller

app/controller/menus_controller.rb

class MenusController < ApplicationController
  active_scaffold :menu do |conf|
    conf.nested.add_scoped_link(:children)  #nested link to children
  end

  protected 

  # If nested let active_scaffold manage everything
  # if not just show all root nodes
  def beginning_of_chain 
    nested? ? super : active_scaffold_config.model.roots 
  end 

  # Assign parent node to just created node
  def after_create_save(record) 
    if (nested? && nested.scope) 
      parent = nested_parent_record(:read) 
      record.send("#{nested.scope}").send(:<<, parent) unless parent.nil? 
    end
  end 
end

5. Starting server and creating menu records

Create records, edit records, delete records,…..

6. Something is missing…. Sorting

app/model/menu.rb

class Menu < ActiveRecord::Base
  acts_as_list
  has_ancestry
end

You have to restart your server to enable sorting feature in your UI.

About these ads