5

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

{“帖子”:{“评论”:[1、2、3]}}

我无法确定如何在 rails 控制器中生成 id 数组。虽然我可以 :include 关联的模型,但它们被包含为哈希数组:

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

关于如何获得数组形式的任何想法?

4

2 回答 2

6

Ember 建议使用 active_model_serializers gem 以兼容格式生成 JSON。

这是 active_model_serializer 文档中的一个示例,可以完全按照您的要求进行操作。是embed :ids关键。

class PostSerializer < ActiveModel::Serializer
  embed :ids

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

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

于 2013-01-20T02:37:22.050 回答
-1

另一种方法是在创建响应传递时:root => true

respond_to do |format|
  format.html # index.html.erb
  format.json { render :json => @posts, :root => true }
end
于 2013-01-20T03:02:47.520 回答