Correct way to exclude attributes from json serialization

Hi

I’m using Mongoid and Rails 3, and I want to serialize one of my
mongoid documents to json for publishing via a controller, e.g.

class ReportController < ApplicationController
respond_to :json

def show
    report = Report.where(:report_id => params[:id]).first
    respond_with report
end

end

This works ok, but pushes out every attribute on the document
including the “internal” mongodb document id, e.g. :

{
_id: 54857324987546, // internal mongoid document id
report_field_a: 1,
report_field_b: 2,
etc
}

I would like to strip this when serializing the report to json, and I
would also like any embedded documents to have their _id properties
excluded too. I have searched for info on as_json, to_json etc but I’m
not sure which is the best practice approach. The closest I can get
is:

class Report
include Mongoid::Document

def as_json(options = {})
serializable_hash({ :except => :_id }.merge(options))
end
end

…and then I need to copy that same as_json definition onto embedded
document definitions too. Is this the rails 3 way of doing
serialization customization?

I tried defining as_json as:

def as_json(options = {})
super({ :except => :_id }.merge(options))
end

but that doesn’t return a hash as I was expecting, it seems to return
the document itself. I’m not entirely sure what’s happening there.

Any pointers are greatfully received!

Cheers
Lee

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs