【问题标题】:ActiveModel::Serializers embed: :ids, include: true not sideloading dataActiveModel::Serializers embed::ids, include: true not sideloading data
【发布时间】:2015-01-06 19:03:38
【问题描述】:

我正在运行 Rails 4.2 - AMS 0.9 应用程序,并且我有(用于说明目的)3 个模型:Foo has_one Bar,has_many Bazes。我只得到响应中的 id,而不是侧面加载的项目。是否有配置选项,或者我错过了什么?

我的 AMS 课程是:

class FooSerializer < ActiveModel::Serializer
   embed :ids, include: true
   has_one :bar, key: :bar    ## For ember-data; it doesn't like "_id"
   has_many :bazes, key: :bazes

   attributes :id, :etc

end

整个 StackOverflow 上都有很多关于 AMS 的主题,我在发布之前阅读了很多,但这让我完全被难住了。

【问题讨论】:

    标签: ruby-on-rails json ember-data active-model-serializers


    【解决方案1】:

    经过一堆实验,我不得不在控制器中调用以下代码:

    format.json { render json: ActiveModel::ArraySerializer.new(@foos, each_serializer: FooSerializer), root: :foos }
    

    root: :foos(顺便说一句,甚至“true”都不起作用,序列化程序本身中的self.root = true 或self.root = :foos 也不起作用)是关键位。

    【讨论】:

    【解决方案2】:

    @Ted 的回答在数组上对我有用,但是当我尝试在 show 方法中序列化时,我当然不能使用 AciveModel::ArraySerializer。在研究为什么 Ted 的答案有效时,我在 AMS 文档中遇到了这条小线

    当控制器不继承自 ActionController::Base 时,手动包含序列化模块

    class ApplicationController < ActionController::API
      include ActionController::Serialization
    end
    

    链接:https://github.com/rails-api/active_model_serializers/tree/0-9-stable#use-serialization-outside-of-actioncontrollerbase

    由于我的 rails 应用程序只有 api,这正是我所需要的。

    【讨论】:

      猜你喜欢
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 1970-01-01
      • 2013-07-19
      • 2017-11-01
      • 1970-01-01
      • 2014-06-19
      相关资源
      最近更新 更多