Math is Hard
Math is Hard

Reputation: 942

Rails 4.2 Active Record Serializer JSON format issue

I have a serializer on rails that has another nested serializer inside like this

class FeedSerializer < ActiveModel::Serializer
  attributes :id

  has_one :user

  def user
    if object.anonymous
        nil
    else
        UserFeedSerializer.new(object.user)
    end
  end
end

I expected the JSON response to be like

{
    "feed": {
        "id": 10
        "user": {
            "id": 10
        }
    }
}

But instead it's doing this:

{
    "feed": {
        "id": 10
        "user": {
            "user_feed": {
                "id": 10
            }
        }
    }
}

Why is it including an extra nest?

Upvotes: 0

Views: 198

Answers (1)

Ahmed Al Hafoudh
Ahmed Al Hafoudh

Reputation: 8429

Because you are passing serializer for user relation, not the User instance itself. Try disabling root attribute wrapping by placeing root false at the top of UserFeedSerializer.

Upvotes: 1

Related Questions