Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-203

Default value for include_root_in_json

    • Type: Icon: Task Task
    • Resolution: Done
    • 12_01_17
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      In ActiveRecord you can set a global default behaviour for including a root node in to_json by setting ActiveRecord::Base.include_root_in_json (the default is true). As all models then inherit from AR::Base they all use that value by default.

      In Mongoid the include Mongoid::Document approach makes it so that every model gets it's own unique accessor for include_root_in_json. Thus it is a hassle if you prefer to not include the root (don't you agree your REST apis become cleaner without it?) as you'll have to set it to false on each of your models by hand.

      I'm currently solving this by letting lose the monkeys to override the included method on ActiveModels JSON Serializer but it's not pretty.

      1. config/initializers/patches.rb
        module ActiveModel::Serializers::JSON
        included do
        extend ActiveModel::Naming
        class_attribute :include_root_in_json
        self.include_root_in_json = false
        end
        end

      One other thing I noticed was that ActiveRecord does not include the root node for has_many associations when they are added through the to_json :include, :methods or :only options. Mongoid however always adds the root node even in nested context which means you end up with very verbose json by default.

      Consider this Parent embeds many children example.

      {
      "parent": {
      "children": [
      {
      "child":

      { "attributes":"values" }

      },
      {
      "child":

      { "attributes":"values" }


      }
      ]
      }
      }

      So to sum it up...

      • Something like Mongoid.config.include_root_in_json = false to set a default would be nice.
      • Embedded and related documents should probably never put additional root nodes in nested context.

            Assignee:
            Unassigned Unassigned
            Reporter:
            dbackeus David Backeus
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: