Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

ruby on rails - acts_as_tree and to_json or from_json

Hello: Does anyone have a solution to convert an acts_as_tree model to json that includes all its nodes? I trued using :include=>:children, but that only goes down to one single level. Any idea how to iterate the whole tree?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a helper (or private method) which is recursive and turns your nested models in to a nested hash, then use to_json to generate a json string.

I needed to generate Json in a HTML/Erb view, but the same idea should apply if you need to generate it from a controller action, or use an Erb template to generate Json. I also needed a (hardcoded) root node, you can skip that if its not required.

categories.html.erb

<script type="text/javascript">
  $(function(){
      var json = {
        id: "node00",
        name: "New Pathway",
        data: {},
        children: 
<%= @categories.select { |c| c.root? && !c.leaf? }.collect { |c| category_to_spacetree_json(c) }.to_json.html_safe %>
      };

      init(json);
  });
</script>

categories_helper.rb

  def category_to_spacetree_json(category)
    hash = {
      :id => category.id,
      :name => category.name,
      :data => '',
      :children => []
    }

    unless category.leaf?
      hash[:children] = category.children.public.collect { |c| category_to_spacetree_json(c) }
    end

    hash        
  end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...