Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Add custom attributes when serializing

#2380

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 = Foo.new params[:foo]
      if @foo.save
        respond_to do |f|
          f.html { redirect_to @foo }
          f.js { render :json => @foo.to_json(:merge => { :html => render_to_string(:action => 'show') }) }
        end
      else
        respond_to do |f|
          f.html { render :action => 'new' }
          f.js { render :json => @foo.to_json(:methods => :errors) }
        end
      end
    end
  end

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.

Reported by Dmitry Ratnikov · March 31st, 2009 @ 12:13 AM

State: wontfix
Milestone: 2.x
Assigned to: Ryan Bigg Ryan Bigg
Importance: none

Activity

  1. Steve St. Martin
    Steve St. Martin
    • 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') }
    

    April 16th, 2010 @ 12:01 AM

  2. Ryan Bigg
    Ryan Bigg
    • State changed from new to wontfix

    Agreed.

    April 16th, 2010 @ 12:12 AM