1
votes

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.

1
Have you tried using self.include_root_in_json = true in User model?mauro_oto
Yeah this works. But I would still like to fix the error at the root of the problem. Since the Serializer should have a consistent behaviour and not change randomly. Thanks!Deutro

1 Answers

0
votes

I figured out how to solve the problem, but I would still like to have an explanation if someone knows whats wrong with the belongs_to.

Changing the belongs_to to has_one works and adds the "user": as JSON root.