如何让Rails以正确的ember.js格式生成JSON? [英] How do I get Rails to generate JSON in the correct format for ember.js?

查看:151
本文介绍了如何让Rails以正确的ember.js格式生成JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ember指南中的模型 http://emberjs.com/guides / models / the-rest-adapter /#toc_relationships 我看到关联应该被指定为一个ids数组:

In the Ember guide on models http://emberjs.com/guides/models/the-rest-adapter/#toc_relationships I see that associations should be specified as an array of ids:


{
post:{
comments:[1,2,3]
}
}

{ "post": { "comments": [1, 2, 3] } }

我无法找出如何在rails控制器中生成ids数组。虽然我可以:包括相关的模型,它们被包括为一组哈希值:

I'm having trouble working out how to generate the array of ids in the rails controller. While I can :include the associated models, they are included as an array of hashes:


{name:Jane's Place rooms:[{id:1},{id:2},{id:3}]}

{"name":"Jane's Place","rooms":[{"id":1},{"id":2},{"id":3}]}



Any ideas on how one would get the array form?

推荐答案

Ember建议使用active_model_serializers gem在一个兼容格式。

Ember recommends using the active_model_serializers gem to generate JSON in a compatible format.

这是一个来自active_model_serializer文档的示例,它几乎完全符合您的要求。 embed:ids 是关键。

Here is an example from the active_model_serializer documentation to do pretty much exactly what you're asking. The embed :ids is the key.

class PostSerializer < ActiveModel::Serializer
  embed :ids

  attributes :id, :title, :body
  has_many :comments
end

https://github.com/rails-api / active_model_serializers

这篇关于如何让Rails以正确的ember.js格式生成JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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