【发布时间】:2018-03-27 15:11:36
【问题描述】:
如何链接多个模型以在 Rails 中呈现为 JSON 对象。 目前我有一个像
这样的渲染语句render json: current_user.role.selected_bids.to_json(include: [:project => {include: [:milestones , :skill_category] } ] )
我想将另一个模型附加到这个 JSON 对象,我可以在其中包含一个与 :milestones 关联的模型。像这样的
render json: current_user.role.selected_bids.to_json
(include: [:project => {include: [:milestones=> {include: [:timetrackers]},
:skill_category]}])
但它会引发语法错误。是否可以进行这种级别的嵌套,还是应该进行另一个 API 调用?
【问题讨论】:
-
您可以使用序列化器来构建 json 或基于视图的解决方案,例如 jbuilder。
-
哦,好吧,但是不能在此处本身包含关联吗?
-
apidock.com/rails/ActiveRecord/Serialization/to_json 查看最后一个区块。 “二级和更高级别的关联也可以工作”
-
@Anton 非常感谢 :)
-
欢迎您! :)
标签: ruby-on-rails json ruby