How do I get Rails to generate JSON in the correct format for ember.js?

↘锁芯ラ 提交于 2019-12-22 06:11:09

问题


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] } }

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}]}

Any ideas on how one would get the array form?


回答1:


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

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




回答2:


Alternative way of doing this is When creating response pass :root => true

respond_to do |format|
  format.html # index.html.erb
  format.json { render :json => @posts, :root => true }
end


来源:https://stackoverflow.com/questions/14421109/how-do-i-get-rails-to-generate-json-in-the-correct-format-for-ember-js

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