front and back-end web development, Leeds, UK


Richard's Blog - Design, coding and life in Japan

Richard

JSON Data for multiple objects and associations in Rails

I am creating a REST API in Rails which outputs JSON data. In some cases I need multiple objects to be pushed out in the data, which is fine until you need to use associations in the mix also.

Example:

form = Form.find(params[:id])
products = Product.all

I am needing these objects plus the child (has_many) form elements of the form object. So I tried:

render :json => [form.to_json(:include=>:form_elements), products]

But the double JSON parsing of the form object created unwanted slashed in the data. I have used the following hack...

render :json => [ActiveSupport::JSON.decode(form.to_json(:include=>:form_elements)), products]

So I decode the JSON data before sending it to the renderer. But if someone knows how to do this in a less hack-ish way then please let me know!

Tags:

This gets the job done, but

This gets the job done, but did you ever find a less hacky way to do it?

I agree

I agree that it is a bit hacky, I didn't find a less hacky way to do it I am afraid, but I don't know the options available in Rails 3 that might help this. Thanks for getting in touch.

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.

Recent Blog Posts