rails-api/active_model_serializers — pull request #166 by gabetax (2012-11-30 19:54:08+00:00)
Title: Update documentation to use ActiveSupport.on_load to disable root

With the current master branch and Rails 3.2.9, it seems that using an config/initializer/ file to set:

``` ruby
ActiveModel::ArraySerializer.root = false
```

does not affect the `_root?` property of any of the defined serializers:

```
1.9.3-p327 :001 > ActiveModel::ArraySerializer.root
=> false
1.9.3-p327 :002 > PostSerializer._root?
=> true
1.9.3-p327 :003 > s = PostSerializer.new Post.first
Post Load (0.5ms) SELECT "posts".* FROM "posts" LIMIT 1
=> #>
1.9.3-p327 :004 > s.to_json
=> "{\"post\":{\"id\":1,\"title\":\"test\",\"body\":\"oh yeah\"}}"
```

If we change this to use:

``` ruby
ActiveSupport.on_load(:active_model_serializers) do
self.root = false
end
```

The serializers inherits the property correctly:

```
1.9.3-p327 :001 > ActiveModel::ArraySerializer.root = false
=> false
1.9.3-p327 :002 > PostSerializer._root?
=> false
1.9.3-p327 :003 > s = PostSerializer.new Post.first
Post Load (0.2ms) SELECT "posts".* FROM "posts" LIMIT 1
=> #>
1.9.3-p327 :004 > s.to_json
=> "{\"id\":1,\"title\":\"test\",\"body\":\"oh yeah\"}"
```

I'm not sure if this should stay as a simple documentation fix, or if we want to fix it so the previous way works still. However, ActiveRecord uses `ActiveSupport.on_load` itself for this exact same purpose in `config/initializers/wrap_parameters.rb`:

``` ruby
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = false
end
```