ruby on rails - Stop nesting data of the active model serializer gem -
i using active model serializer gem, , works fine now. have stumbled upon issue, wan't stop nesting of data retrieved.
lets have 3 models:
users
has_many orders
has_many addresses
.
normally in users serializer class
have have has_many
orders model
, , in orders model serializer have has_many
relationship addresses
.
i have users controller, don't want orders out, not nested addresses. can done without creating whole new serializer class?
update, clarify:
i have following 3 models:
class user < activerecord::base has_many orders end class orders < activerecord::base belongs_to user has_many addresses end class addresses < activerecord::base belongs_to order end
i have 3 serializers identical models.
for orders api retrieve addresses well, when query users wants associated orders , not addresses. when query users both returns orders , addresses, since have has_many addresses orders.
is option create separate serializers 2 options (it doesn't feel dry)?
you can use default_serializer_options method defines serializer options serializers , children used controller.
#users_controller.rb class userscontroller < applicationcontroller def default_serializer_options { include_addresses: false } end end
then override initialize method in order serializers check serializer options include_addresses flag:
# order_serializer.rb class orderserializer < activemodel::serializer def initialize(object, options = {}) options.reverse_merge! include_addresses: true # default should include addresses @include_addresses = options[:include_addresses] super end def include_addresses? @include_addresses end end
and that's it. specify option in every controller don't need addresses nested.
Comments
Post a Comment