# Eager fetching returning JSON results

**URL:** <https://www.ruby-forum.com/t/eager-fetching-returning-json-results/160307>\
**Category:** Rails\
**Created:** [February 14, 2009, 2:27am UTC](https://www.ruby-forum.com/t/eager-fetching-returning-json-results/160307 "2009-02-14T02:27:32Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![builtbysimple](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/aca169/32.png) [@builtbysimple](https://www.ruby-forum.com/u/builtbysimple)\
**Post date:** [February 14, 2009, 2:27am UTC](https://www.ruby-forum.com/t/eager-fetching-returning-json-results/160307/1 "2009-02-14T02:27:32Z")

</div>

All,

I have a many\_to\_one relationship object between products and  
categories and I want to return the category too using JSON results  
but it seems that rails only gives back the products JSON object on  
the view layer. This is the piece of code:

```
    @products = Product.find(:all, :include => [:category] )

    respond_to do |format|
        format.json {render :json => [@products]
    end

```

Have I missed something? I thought by doing this I have enabled the  
eager fetching? Or does eager fetching does not work with JSON  
results?

Thanks in advance.

–  
If you can’t believe in God the chances are your God is too small.

Read my blog: [http://joshuajava.wordpress.com/](http://joshuajava.wordpress.com/)  
Follow me on twitter: [http://twitter.com/jpartogi](http://twitter.com/jpartogi)

---

<div class="post-metadata">

**Author:** ![builtbysimple](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/aca169/32.png) [@builtbysimple](https://www.ruby-forum.com/u/builtbysimple)\
**Post date:** [February 14, 2009, 11:31am UTC](https://www.ruby-forum.com/t/eager-fetching-returning-json-results/160307/2 "2009-02-14T11:31:41Z")

</div>

On Feb 14, 1:26 am, Joshua P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> format.json {render :json => [@products]
> end
> 
> ```

There’s 2 separate things: the :include option on Product.find just  
ensures those associations are loaded  
To have them in your json (or xml) output you need to pass that to  
to\_json or to\_xml, ie render :json =\> @products.to\_json(:include  
=\> :category)

Fred

---

<div class="post-metadata">

**Author:** ![builtbysimple](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/aca169/32.png) [@builtbysimple](https://www.ruby-forum.com/u/builtbysimple)\
**Post date:** [February 14, 2009, 1:08pm UTC](https://www.ruby-forum.com/t/eager-fetching-returning-json-results/160307/3 "2009-02-14T13:08:56Z")

</div>

Darn,

I returned an array object besides that products instance, giving that  
to\_json will give backslashes to the quotes.

On Feb 14, 9:31 pm, Frederick C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
