Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activerecord associations as JSON with Grape

Is there a simple way to return activerecord models with associations as JSON using the Grape microframework?

get 'users' do
  User.includes(:address)
end

This snippet isn't working and User.includes(:address).to_json(include: :address) will get encoded twice as JSON. (To use the to_json method on my own doesn't feel right anyway)

like image 930
schickling Avatar asked Dec 25 '22 19:12

schickling


1 Answers

You might want to use #as_json instead.

So you can do

User.includes(:address).as_json(include: :address)

and that gives you a hash instead of a json string.

like image 166
Ismael Avatar answered Jan 06 '23 20:01

Ismael