ActiveRecord关联的JSON与葡萄 [英] Activerecord associations as JSON with Grape

查看:145
本文介绍了ActiveRecord关联的JSON与葡萄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法,使用葡萄microframework返回ActiveRecord模型与各协会作为JSON?

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

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

这片段是不是工作, User.includes(:地址).to_json(包括:地址)将获得EN codeD两倍JSON。 (要使用 to_json 对我自己的方法,感觉不对反正)

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)

推荐答案

您可能需要使用 #as_json 代替。

所以,你可以做

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

这给了你一个散列,而不是一个JSON字符串。

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

这篇关于ActiveRecord关联的JSON与葡萄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆