在Rails中使用ActiveModel :: Serializer – JSON数据在json和index响应之间有所不同

我正在使用active_model_serializers gem来控制序列化数据,并看到一些奇怪的行为。 我的代码看起来像这样:

模型和序列化器

 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 

view(app / views / users / index.html.erb)

 ...  $(function(){ // using a backbone collection to manage data App.users = new App.Collections.Users(); });  

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

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

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

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

我看不出我可能做错了什么 – 任何输入都会有所帮助。 谢谢。

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

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

原因是在.to_json方法中拾取了序列化程序,序列化程序不会覆盖 .to_json方法。

@Gagan这适合我:

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