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

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to