Rails model to recursive json

ruby, ruby-on-rails

Solution

JSON in Rails works through two methods:

`as_json` is responsible for creating a hash representation of the object whereas `to_json` converts that hash object representation to JSON.

So what you need to do is define the as_json method in your model to include what you want.

def as_json
 {
   :other_options => value,
   :submenu => self.submenus.collect { |n| n.as_json }
 }
end

This is a very crude implementation, but it will recursively visit all submenus (as submenus are menus themselves) and render them to a Hash that then gets translated to JSON.

Problem

I had a Menu model, that has submenus of same type. Something like: - level 1 - level 1.1 - level 1.2 - level 2 - level 2.1 - ... So, I need a way to include in my json, all levels, in a recursive way.

Original source