stefankroes / ancestry

Organise ActiveRecord model into a tree structure
MIT License
3.72k stars 458 forks source link

Do I still need to write an arrange_as_array routine to get a children inclusive ordered list? #602

Closed mices closed 1 year ago

mices commented 1 year ago

Is it still necessary to do this? Because my app errors out on this and I can't find out why

    def self.arrange_as_array(options={}, hash=nil)
    hash ||= arrange(options)

    arr = []
    hash.each do |node, children|
      arr << node
      arr += arrange_as_array(options, children) unless children.nil?
    end
    arr
  end
kshnurov commented 1 year ago

arrange_as_array is some obsolete method. Check README on arrangment

mices commented 1 year ago

Can you help please

class ItemType < ApplicationRecord
  has_ancestry
    has_many    :item_properties
    has_many    :item_types, foreign_key: :parent

  def name_for_selects
    "#{'-' * depth} #{name}"
  end

  def possible_parents
    parents = ItemType.arrange(:order => 'name')
    return new_record? ? parents : parents - subtree
  end
end
view:
    <td><%= f.collection_select :item_type_id, @item_types, :id, :name_for_selects, prompt: true, selected: @item.item_type_id %>

error:
ActionView::Template::Error (undefined method `name_for_selects' for {"id"=>1, "name"=>"General", "description"=>"", "created_at"=>Sun, 03 Nov 2019 13:58:08.000000000 UTC +00:00, "updated_at"=>Mon, 18 Nov 2019 00:00:16.000000000 UTC +00:00, "parent_id"=>nil, "lft"=>"1", "rgt"=>"2", "depth"=>0, "children_count"=>0, "ancestry"=>nil, "children"=>[]}:Hash
10:36:34 web.1  | 
10:36:34 web.1  |           value.respond_to?(:call) ? value.call(item) : item.public_send(value)
10:36:34 web.1  |                                                             ^^^^^^^^^^^^):

UPDATE: @kbrock added a few back ticks for formatting purposes. Sorry if you didn't want this)

kbrock commented 1 year ago

so the error read that you are expecting a an ItemType object, but you have a hash.

Would you share how you set @item_types in your controller?

mices commented 1 year ago

OK I found that my mistake was setting items using arrange_serializable @item_types=ItemType.arrange_serializable Changing it to ItemType.all solved that error

kbrock commented 1 year ago

@mices has this been solved? Would you close if it has or add more comments to help us help you?

mices commented 1 year ago

Yes I found it in the wiki