Prevent stack overflow when serializing self-referential data as JSON

I originally encountered this problem when dealing with the following data structure:

```ruby
class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, through: :memberships

  def as_json(options = {})
    super(options.merge(include: [:users]))
  end
end

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, through: :memberships

  def as_json(options = {})
    super(options.merge(include: [:groups]))
  end  
end
```

I had situations in which I needed to display all the groups in which a user was a member and others in which I needed to display all the users who were members in a group.  While I was able to work around this issue by using the higher-level membership object in the following manner

```ruby
class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group

  def as_json(options = {})
    super(options.merge(methods: [:user, :group]))
  end
end
```
this change did require some significant restructuring of the application, specifically removing the cyclical references between user and group and only consuming memberships.

I believe something like the reference tracking in this commit would make structures of this nature easier to work with and allow for creating more nuanced API interfaces.