Lee Henson
2011-Feb-03 19:15 UTC
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 -- 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-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
Seemingly Similar Threads
- "best practices" for Rails serving RESTful JSON services for use by AngularJS, Ember.js, etc.
- help writing a usb hid driver for existing ups
- as_json and self-referential associations
- ActiveSupport 2.3.5 and json 1.2.0 gem
- when use mongoid , Model.count can't work.