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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
JSON in Rails works through two methods:
as_jsonis responsible for creating a hash representation of the object whereasto_jsonconverts 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.
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.