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.