I currently write an API with Rails. After watching the RailsCast about ActiveModel::Serializer I wanted to try them out.
Short overview over my current models:
class Club < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
validates :userName, presence: true
belongs_to :club
end
Creating a user returns the following JSON:
{"id":1,"userName":"Test","firstName":"Test","lastName":"Test","created_at":"2014-10- 10T12:42:12.186Z","updated_at":"2014-10-10T12:42:12.186Z","city":"Test","street":"Test","mail":"Test","club_id":1}
As in the example from the ActiveModel::Serializer page I implemented the UserSerializer as following:
class UserSerializer < ActiveModel::Serializer
attributes :id, :userName, :firstName, :lastName, :mail, :street, :city, :club_id
end
This does add "user": as root to my JSON format. Additionally the example shows to add
belongs_to :club
to the Serializer. But if I add the belongs_to I do not get the "user": as root for my JSON. Is this intended behaviour? Is there a way to change this? After additional testing it seems that the "user": root element is randomly -did not find a pattern yet- added or omitted.
I tried to add
root: true
to my users_controller which did not help either.
self.include_root_in_json = true
inUser
model? – mauro_oto