How do I use active_model_serializers to include by default all attributes and filter them?

StackOverflow https://stackoverflow.com/questions/15305916

Вопрос

I'm using active_model_serializers and would like to find a way to include all model's attributes by default and then to use something like this

       exclude :date_created, :first_name

to specify the ones that I don't need.

Until now I didn't find a way to specify the exported attributes besides the one in the docs and that is done by enumerating all of the needed attributes:

       attributes :title, :body
Это было полезно?

Решение

You could do something like this on your model serializer (taking an example of User as the model):

class UserSerializer < ApplicationModelSerializer
   attributes(*User.attribute_names.map(&:to_sym))
end

More information about ActiveRecord attribute_names can be found here: http://apidock.com/rails/ActiveRecord/AttributeMethods/attribute_names

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top