在Rails中使用ActiveModel :: Serializer-JSON和索引响应之间的JSON数据有所不同 [英] Using ActiveModel::Serializer in Rails - JSON data differs between json and index response

查看:84
本文介绍了在Rails中使用ActiveModel :: Serializer-JSON和索引响应之间的JSON数据有所不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 active_model_serializers gem来控制序列化数据,并看到一些奇怪的行为.我的代码如下:

I'm using active_model_serializers gem to control the serialization data, and seeing some odd behavior. My code looks like so:

class User
  include Mongoid::Document
  field :first_name, :type => String
  field :last_name,  :type => String

  def full_name
    first_name + " " + last_name
  end
end

class UserSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :full_name
end

控制器

class UsersController < ApplicationController
  respond_to :json, :html

  def index
    @users = User.all
    respond_with @users
  end
end

视图(app/views/users/index.html.erb)

...
<script type="text/javascript">
  $(function(){
    // using a backbone collection to manage data
    App.users = new App.Collections.Users(<%= @users.to_json.html_sage %>);
  });
</script>

现在,在渲染视图时,我发现数据中缺少full_name属性(通过模型中的方法生成):

Now, when I render the view, I see that the full_name attribute (generated via method in the model) is missing from my data:

{
  "id": 2,
  "first_name": "John",
  "last_name": "Doe"
}

当我访问/users.json(我的routes.rb文件中有resources :users)时,我看到了正确的JSON:

When I access /users.json (I have resources :users in my routes.rb file), I see the correct JSON:

{
  "id": 2,
  "first_name": "John",
  "last_name": "Doe",
  "full_name": "Jonn Doe"
}

我看不到我可能做错了什么-任何输入都会有所帮助.谢谢.

I couldn't see what I might be doing wrong - any input will help. thanks.

推荐答案

您没有在HTML视图中使用序列化程序.试试这个:

You are not using your serializer in the HTML view. Try this:

App.users = new App.Collections.Users(<%= UserSerializer.new(@users).to_json.html_safe %>);

App.users = new App.Collections.Users(<%= UserSerializer.new(@users).to_json.html_safe %>);

这样做的原因是在respond_with方法中拾取了序列化程序,序列化程序进行了

The reason for this is that the serializer is picked up in the respond_with method, the serializer does not overwrite your .to_json method.

这篇关于在Rails中使用ActiveModel :: Serializer-JSON和索引响应之间的JSON数据有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆