Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails nested association. in render :json

Existing questions have gotten me 90% of the way to what I want, but there's a hitch.

I have a CheckIns model, and a Person model. CheckIns belong to People.

In my controller, I have this code:

data = CheckIn.all
render json: { data: data }

For each CheckIn, I'd like to nest the associated Person in it. Past StackOverflow questions suggest I do this:

data = CheckIn.all
render json: data.to_json include: :person

But, this makes it difficult to nest my data inside of a wrapper JSON object, like I originally did, because to_json creates a string, not a Hash.

I want the wrapper JSON object so that I can follow a standardized JSON output, where data is always in a data: field, and other metadata can be attached to the response.

How can I get the effect of the include: flag for to_json, while also keeping the wrapper object? In particular, this is not a valid answer for me, since it's really ugly:

data = CheckIn.all
render json: { data: JSON.parse data.to_json(include: :person) }

Thanks! Hope there's an idiomatic way to do this in Rails.

like image 258
osdiab Avatar asked Jan 18 '26 02:01

osdiab


1 Answers

Active Records support eager loading http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

loading checkins associated with user:

@users = User.all.includes(:checkins)

will be querying:

User Load (0.2ms)  SELECT "users".* FROM "users"
Checkin Load (0.1ms)  SELECT "checkins".* FROM "checkins"  WHERE "checkins"."user_id" IN (1)

but this wont let you render your nested objects, what you are looking for is something to Decorate your data

take a look at https://github.com/nesquena/rabl or github.com/rails/jbuilder

You will be able to provide decorator with templates and data object to render

like image 176
vovko Avatar answered Jan 19 '26 19:01

vovko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!