mongoid/mongoid — Issue #1756: as_json override no longer works for embedded documents
Author: thegrubbsian
Created: 2012-02-23 23:55:59+00:00
State: open

In a recent upgrade from Mongoid 2.3.4 to 2.4.5 I had a few specs start to fail and the root cause seems to be that my override of as_json doesn't seem to be working for embedded documents anymore. I have the following monkey patch that overrides as_json:

module Mongoid
module Document

def as_json(options={})
attrs = super(options)
attrs["id"] = self.persisted? ? self._id : nil
attrs
end

end
end

In Mongoid 2.3.4 my specs pass for this, but when I update to 2.4.5 they do not. What's odd though, is that it looks like the root document still gets the proper treatment, just not the embedded ones. Here's an example spec that fails:

describe "#project" do

let(:account) { Factory.create(:account) }
let(:project) { Factory.create(:project, :account_id => account.id) }

before do
controller.stub(:authorize_member_user! => true)
controller.stub(:current_project => project)
end

it "returned JSON should include id property for project phases" do
get :project, { :account_permalink => account.permalink, :project_permalink => project.permalink }
json = JSON.parse(response.body)
json["phases"].all? { |p| p["id"].present? }.should be_true
end

end