This project is archived and is in readonly mode.

#2380 ✓wontfix
Dmitry Ratnikov

Add custom attributes when serializing

Reported by Dmitry Ratnikov | March 31st, 2009 @ 12:13 AM | in 2.x

This patch allows to add additional attributes when serializing via to_json or to_xml.

Specific use-case I have for it is when servicing ajax creation requests. As response, I want to return the created object information, but I would like to also provide information on how to render it (basically html snippet) so that js client can use it to update dom in a consistent manner. So I render the show template for it and mix into the rest of json data for the model:

  class FoosController < ApplicationController
    def create
      @foo = params[:foo]
        respond_to do |f|
          f.html { redirect_to @foo }
          f.js { render :json => @foo.to_json(:merge => { :html => render_to_string(:action => 'show') }) }
        respond_to do |f|
          f.html { render :action => 'new' }
          f.js { render :json => @foo.to_json(:methods => :errors) }

The patch touches following files:

  • active_record/serialization.rb to implement support of the :merge option
  • test/cases/json_serialization_test.rb and test/cases/serialization_test.rb to reflect the new behavior
  • active_record/serializers/json_serialization.rb to document the new feature.

Hope that sounds useful.

-- Dmitry

PS Current implementation allows the merged attributes to override the defaults. Also, it ignores excepted attributes (specified via :except option). The only reason they behave like that is because it made most sense to me.

Comments and changes to this ticket

  • Steve St. Martin

    Steve St. Martin April 16th, 2010 @ 12:01 AM

    • Assigned user set to “Ryan Bigg”

    suggesting mark as wontfix, serializing should serialize the object/model, any custom attributes should be on the model if they are needed to be serialized. the use case above could likely be solved with something like

     render :json => { :foo => @foo.to_json, :html => render_to_string(:action => 'show') }
  • Ryan Bigg

    Ryan Bigg April 16th, 2010 @ 12:12 AM

    • State changed from “new” to “wontfix”


Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

People watching this ticket