Forum: Ruby on Rails Eager fetching returning JSON results

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Joshua P. (Guest)
on 2009-02-14 03:27
(Received via mailing list)

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]

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

Thanks in advance.

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

Read my blog:
Follow me on twitter:
Frederick C. (Guest)
on 2009-02-14 12:31
(Received via mailing list)
On Feb 14, 1:26 am, Joshua P. <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)

Joshua P. (Guest)
on 2009-02-14 14:08
(Received via mailing list)

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>
This topic is locked and can not be replied to.