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.