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
...
<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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With