Using ActiveModel::Serializer in Rails - JSON data differs between json and index response

给你一囗甜甜゛ 提交于 2019-11-29 15:39:37

问题


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

model & serializer

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

controller

class UsersController < ApplicationController
  respond_to :json, :html

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

view (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>

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"
}

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.


回答1:


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 %>);

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.




回答2:


@Gagan this works for me:

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



来源:https://stackoverflow.com/questions/13367656/using-activemodelserializer-in-rails-json-data-differs-between-json-and-inde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!