Activerecord associations as JSON with Grape

非 Y 不嫁゛ 提交于 2019-12-10 07:27:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!