Dennis
Dennis

Reputation: 21

Rails Active_Model_Serializer Relationships not beeing serialized

I'm building an Rails API with the active_model_serializer gem.

The Problem I've got is, that I can't serialize relationships even doe I created a serializer for them.

First of all, here are my Models:

user.rb

class User < ApplicationRecord
has_many :component

component.rb

class Component < ActiveRecord::Base
  belongs_to :user

  has_many :profiles
end

And here is my users_controller.rb:

class UsersController < ApplicationController

    def show
        @user = User.first

        render(                              //
            status: :ok,                     //
            json: @user,                     //updated
            serializer: UserSerializer       //
        )                                    //
    end
end

And my serializers.

user_serializer.rb

class UserSerializer < ApplicationSerializer
  attributes :id, :component

  has_many :component, serializer: ComponentSerializer //updated
end

component_serializer.rb

class ComponentSerializer < UserSerializer
  attribute :id, :profile, :test

  def test
    'this is a test'
  end
end

As you may see in the attached image, I can serialize the attributes of the 'User' but cant edit the attributes of the 'component'.

JSON Request with component_serializer.rb

If i delete the file 'component_serializer.rb' all attributes are been listed under 'component' in the relationship attribute, as beeing showed in the second screenshot.

JSON Request without component_serializer.rb

Am I missing anything? I searched now for quite some time but didn't find a answer.

Don't know if this matters but I'm using Rails 5.0.1 on a linux server, with the 'active_model_serializers', '~> 0.10.0' gem.

Thanks in advance

Upvotes: 1

Views: 2111

Answers (1)

Dennis
Dennis

Reputation: 21

Ok after searching a while, I just found out, that this question was been asked already ^^

Active Model Serializers data attributes from associations are not loading

Could anyone tell me if this is the recommended way to serialize nested models?


Just a quick update. If someone else is running to this problem.

This Tutorial from GoRails explains why a serializer doesn't affect the attributes in the relationship of an Model and how to include the nested Model instead.

https://www.youtube.com/watch?v=lQOLrycmXC4

Upvotes: 1

Related Questions