Model description:
User, Widget, Purchase
User
has_many :purchases
has_many :widgets, :through => :purchases
Widget
has_many :purchases
has_many :users, :through => :purchases
Purchase
belongs_to :user
belongs_to :widget
Hope that makes sense and is correct for the below.
Right, in my controller, I have current_user.
I wish to render a nested JSON response for use eventually with jquery templates.
Like this would be ideal:
{
"purchases": [
{
"quantity": 200,
"price": "1.0",
"widget": {
"name": "Fantastic Widget",
"size": "Large"
}
},
{
"quantity": 300,
"price": "3.0",
"widget": {
"name": "Awesome Widget",
"size": "Medium"
}
}
]
}
This:
render :json => current_user.to_json(:include => [:purchases, :widgets])
Will render some current_user details (not really relevant) and then purchases and widgets at the same level.
This works (outputs some current user details but thats not my main gripe at the moment):
render :json => current_user.to_json({:include => :purchases })
But obviously only outputs purchase data. I cannot get a nested include to work (should it work?) even after looking at this sample:
konata.to_json(:include => { :posts => {
:include => { :comments => {
:only => :body } },
:only => :title } })
From here and this existing stackoverflow question.
So I’ve just got myself thoroughly confused. Help appreciated.
I would look into utilizing the as_json method in your models to get the desired output. Adding the following to your models should get you going in the right direction.
Once you’ve added these you’d simply user
to_jsonon your user instance and it should output correctly.