Search code examples
rubyactive-model-serializers

Ruby model | Why is model empty and serializer contains properties?


I'm very new to ruby and can not understand this situation.

I'm using active_model_serializers to generate model and serializer. Now after runing

$ rails g resource post title:string body:string

two files was generated.

  1. app/model/post.rb
  2. app/serializers/post_serializer.rb

So far so good.

But why is the model object (post.rb) empty and has no properties?

class Post < ActiveRecord::Base

end

And why the serializer object contains the properties I defined for a model object? I mean serializer -> component which DO serialization

class PostSerializer < ActiveRecord::Base
    attributes :id, :title, :body
end

Solution

  • As per documentation in Active Model serializers

    The attribute names are a whitelist of attributes to be serialized.

    Active Model serializers are means to selectively transform your model into JSON as per API needs, instead of emitting all the attributes of the Active Model model.

    Hence, the attributes are explicitly listed in Active Model Serializer classes