0

I wanted to render my model to json and include it's nodes when using acts_as_tree. I found this post and it helped alot: acts_as_tree and to_json or from_json

My only question is how to implement this in my controller. I want to return the json in my controller.

So far I have this:

 respond_to :json, :html

  def index
    @categories = Category.all
    respond_with(@categories)
  end

But before returning @categories I'd like to call this on it: <%= @categories.select { |c| c.root? && !c.leaf? }.collect { |c| category_to_spacetree_json(c) }.to_json.html_safe %> But it looks like this can only be called from the view.

How do I do this from my controller?

Thanks!

Community
  • 1
  • 1
  • Rails flow is like this: controller -> model -> view So you have to follow this. and use `respond_to :json` instead of `respond_to :json, :html` to return only in :json format – RAJ Jul 02 '12 at 08:00

1 Answers1

0

Have you tried this?

In the controller:

def index
  @categories = Category.all
  respond_with(@categories.select{ |c| c.root? && !c.leaf? }.collect{ |c| category_to_spacetree_json(c) })
end

In the view:

<%= @categories.html_safe %>
zsquare
  • 9,916
  • 6
  • 53
  • 87