Correct way to exclude attributes from json serialization


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


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,

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

class Report
include Mongoid::Document

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

…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))

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!


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