渲染JSON时未使用ActiveModel :: Serializer

时间:2015-05-23 19:30:38

标签: ruby-on-rails ruby json serialization

我遇到了Rails中的Serializers问题。我正在尝试为我的模型渲染自定义json。为此,我将active_model_serializer添加到我的Gemfile中并编写了一些Serializers。问题是,当我渲染JSON时,它渲染我的整个对象而不是调用序列化器。

这是我的代码

用户序列化程序

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email
end

用户模型

# Class model for users
class User < ActiveRecord::Base
  ...
end

响应模型

class Response
  attr_accessor :status, :data
end

显示方法

def send_response(*args)
  r = Response.new
  r.status = args[0] # This is the HTTP code
  r.data = args[1] # This is a user object
  render json: r, status: r.status
end

的Gemfile

source 'https://rubygems.org'

gem 'rails', '4.2.0'
gem 'pg'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'devise'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'omniauth'
gem 'active_model_serializers'

group :development, :test do
  gem 'byebug'
  gem 'web-console', '~> 2.0'
  gem 'spring'
end

1 个答案:

答案 0 :(得分:0)

您还必须为Response创建序列化程序。将普通对象传递给render json:时,它只会尝试在对象上调用.to_json。它不知道嵌套对象甚至存在序列化器。

class ResponseSerializer < ActiveModel::Serializer
  attributes :title, :body
  belongs_to :user
end

-

def send_response(*args)
  r = Response.new
  r.status = args[0] # This is the HTTP code
  r.data = args[1] # This is a user object
  render json: r, status: r.status
end