2014-10-04 57 views
3

我一直在寻找很多东西,还没有找到解决方案。active_model_serializers不工作在rails-api

我有轨-API应用程序 和简单的模型,控制器和串行

,但是当我试图让指数路线,我得到标准导轨JSON序列化没有。

class Tag < ActiveRecord::Base 
end 

class TagSerializer < ActiveModel::Serializer 
    attributes :id, :title 
end 

class TagsController < ApplicationController 
    def index 
    render json: Tag.all 
    end 
end 

我得到:

[ 
    tag: { 
    id: 1, 
    title: 'kifla' 
    }, 
    tag: 
..... 

我想:

[ 
    { id: 1, title: 'kifla'}, 
    { ..... 

回答

17

貌似你试图禁用JSON输出的根元素

这是如何实现的可能取决于您使用的是哪个版本的active_model_serializers

0.9.x,你可以做这样的事情在Rails初始化:

# Disable for all serializers (except ArraySerializer) 
ActiveModel::Serializer.root = false 

# Disable for ArraySerializer 
ActiveModel::ArraySerializer.root = false 

或者简单地说,在你的控制器动作:

class TagsController < ApplicationController 
    def index 
    render json: Tag.all, root: false 
    end 
end 

欲了解更多信息,这里有链接到相关章节最近版本的自述文件页面。

https://github.com/rails-api/active_model_serializers/tree/0-9-stable#disabling-the-root-element

https://github.com/rails-api/active_model_serializers/tree/0-8-stable#disabling-the-root-element

-

注意,请务必同时,你实际上包括处理序列化的代码,为ActionController的正在:: API默认情况下不会。例如,

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

看来,这不是我唯一的问题,接受root elemnt问题,我的序列化程序根本不会被调用,就像它不存在一样。我一直在寻找网络,我发现人们做的很少,但没有人帮助我。 – Azaryan 2014-10-22 21:36:55

+0

Zamith的下一个答案解决了序列化程序没有陷入渲染步骤的问题,并且可能值得编辑这个答案来包含它。 – 2015-03-17 06:05:51

+0

只需添加'include ActionController :: Serialization'就可以完成(Rails 5 API-only)。 – 2016-04-12 16:46:34

4

我有同样的问题,使用最新的轨道-API 4.2.0beta时

串行器没有得到回升。我将rails-api降级到了4.1.5,并且工作。 不要忘记从配置中删除

config.active_record.raise_in_transactional_callbacks = true 

/application.rb中,将之前的4.2.0

+1

现在已经修复为0.9.3。您可以在这里阅读Github主题:https://github.com/rails-api/active_model_serializers/issues/641 – iHiD 2015-02-09 12:09:24

+0

嘿谢谢!这听起来不错:) – florigee 2015-02-10 12:38:07

31

这是因为序列被默认轨-API不加载产生错误的版本。你必须这样做:

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

这解决了我的问题。 +1 – sergserg 2015-07-11 02:45:55

+0

是的,这是问题所在。 – SpacyRicochet 2016-01-29 12:16:33

+0

的确如此,如果你的ApplicationController继承自ActionController :: API,那么你应该手动包含序列化 – 2017-01-14 17:55:27

3

如果您使用的是最新版本,它似乎根据这一点,你不能设置默认的适配器了:

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

的解决方法是使用

render json: object_to_render, adapter: :json 

此外,它没有必要再补充一点:

include ::ActionController::Serialization 

看到Rails api如何在没有详细文档的情况下将版本更改为版本令人沮丧。