zorab47 / active_admin-sortable_tree

Show ActiveAdmin index as a nested tree with drag'n'drop
MIT License
162 stars 127 forks source link

Add an ordering_attribute to optionally override sorting_attribute. #24

Closed westonplatter closed 8 years ago

nebirhos commented 10 years ago

Hi @westonplatter! I can't figure out the difference between sorting_attribute and ordering_attribute. How can it be used?

westonplatter commented 10 years ago

@nebirhos the reason I added the ordering attribute is that I wanted to sort my collection items by their label or title rather than their ancestry db column.

To use it, you'd do set your config like this,

ActiveAdmin.register Page do
    sortable tree: true,
             sorting_attribute: :ancestry,
             ordering_attribute: :title,
             parent_method: :parent,
             children_method: :children,
             roots_method: :roots,

which would result in something like this since the ordering is done by title, not ancestry or id.

- title: "node 1", ancestry: "", id: 2
  - title "abc", ancestry: 2, id: 3
  - title "xyz", ancestry: 2, id: 1
nebirhos commented 10 years ago

Ok, but can't you obtain the same result setting sorting_attribute: :title? In your code ordering_attribute seems just an alternative for that.

nathanaelkane commented 10 years ago

@nebirhos it wouldn't give the same result because title probably can't be used for saving the position when dragging and dropping. The new attribute is only for displaying nodes in a certain order on the index page.

I solved this by using custom methods for children_method and roots_method, e.g.

# app/admin/tree_node.rb
ActiveAdmin.register TreeNode do
  sortable \
    :tree => true,
    :sorting_attribute => :ancestry,
    :children_method => :children_ordered_by_name,
    :roots_method => :roots_ordered_by_name
end

# app/models/tree_node.rb
class TreeNode < ActiveRecord::Base
  has_ancestry

  def self.roots_ordered_by_name
    roots.order(:name)
  end

  def children_ordered_by_name
    children.order(:name)
  end
end
westonplatter commented 10 years ago

@nebirhos Great question because it does look like duplicated code at first.

As @nathanaelkane mentioned, :sorting_attribute is used to save position (see https://github.com/nebirhos/activeadmin-sortable-tree/blob/master/lib/active_admin/sortable/controller_actions.rb#L33). In my case I wanted a parameter to sort by without saving data to.

donaldpiret commented 10 years ago

I think I'm looking for something similar to what @westonplatter would like to have. A version of this plugin without any saving going on. Is that somehow possible?