Forum: Ruby on Rails render :json and associations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
pat.osterday (Guest)
on 2008-12-20 17:19
(Received via mailing list)
Is there any way to use the to_json includes when using
"render :json"?

I've got this:

format.json { render :json => { :order => @orders } }

But I'd also like to include the address (order.address) association.
The "to_json" method has all these options, but I don't see how I can
use that with render :json.  If I tack on the to_json to @orders the
render :json escapes the whole thing.  I'm using Ext JS on the client
side.

Thanks!
Frederick C. (Guest)
on 2008-12-20 17:20
(Received via mailing list)
On Dec 20, 2:55 pm, "pat.osterday" <removed_email_address@domain.invalid> wrote:
> Is there any way to use the to_json includes when using
> "render :json"?
>
> I've got this:
>
> format.json { render :json => { :order => @orders } }
>

render :json => @orders.to_json(...)

Fred
rp8 -. (Guest)
on 2008-12-20 20:55
use eager loading on your @orders with :include option or use :select to
add attributes from address if you only need limited data from address
and performance is a concern.

Regards,

rp8
=======================
http://lun.competo.com/

Frederick C. wrote:
> On Dec 20, 2:55�pm, "pat.osterday" <removed_email_address@domain.invalid> wrote:
>> Is there any way to use the to_json includes when using
>> "render :json"?
>>
>> I've got this:
>>
>> format.json { render :json => { :order => @orders } }
>>
>
> render :json => @orders.to_json(...)
>
> Fred
(Guest)
on 2008-12-22 17:17
(Received via mailing list)
This works, but what if I want to add other json object that aren't in
orders?  Ext JS needs a "count" param for it's client side
pagination.  So I originally had this:

format.json { render :json => { :order => @orders, :count =>
@orders.size } }

I couldn't figure out how to use to_json in this situation.

On Dec 20, 10:19 am, Frederick C. <removed_email_address@domain.invalid>
(Guest)
on 2008-12-22 17:17
(Received via mailing list)
I do have includes on the finder, but the associates are not sent with
the json output.

For now I wound up just building my own hash and returning that.
Frederick C. (Guest)
on 2008-12-22 17:18
(Received via mailing list)
On Dec 22, 2:31 pm, "removed_email_address@domain.invalid" 
<removed_email_address@domain.invalid> wrote:
> This works, but what if I want to add other json object that aren't in
> orders?  Ext JS needs a "count" param for it's client side
> pagination.  So I originally had this:
>
> format.json { render :json => { :order => @orders, :count =>
> @orders.size } }

format.json { render :json => { :order => @orders, :count =>
@orders.size }.to_json }

Fred
This topic is locked and can not be replied to.