问题
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)
回答1:
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.
回答2:
This sounds like a good application for the grape-active_model_serializers plugin.
It will manage serializing the objects into JSON for you, including embedding associations by default, and it's extremely configurable if you want/need to override its defaults.
来源:https://stackoverflow.com/questions/19137521/activerecord-associations-as-json-with-grape