Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 682
sa125 Avatar asked Jan 16 '23 01:01

sa125


1 Answers

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.

like image 123
harm Avatar answered Jan 17 '23 15:01

harm