Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #9677 (closed defect: fixed)

Opened 8 months ago

Last modified 8 months ago

[PATCH] Add :include to ActiveRecord::Base#to_json

Reported by: chuyeow Assigned to: core
Priority: normal Milestone:
Component: ActiveRecord Version: edge
Severity: normal Keywords: ActiveRecord, JSON rails2
Cc:

Description

r7519 is missing support for the :include option like for ActiveRecord::Base#to_xml. This patch adds that so you can do things like:

json = @david.to_json(:include => :posts)
# or even...
json = @david.to_json(
  :include => {
    :posts => {
      :include => {
        :taggings => {
          :include => {
            :tag => { :only => :name }
          }
        }
      }
    }
})

Attachments

add_includes_to_to_json.diff (10.7 kB) - added by chuyeow on 09/25/07 16:14:17.
Add :includes option to ActiveRecord#to_json
add_includes_to_to_json.2.diff (8.8 kB) - added by chuyeow on 09/25/07 16:16:38.
Add :includes option to ActiveRecord#to_json
add_includes_to_serializer.diff (13.4 kB) - added by chuyeow on 09/26/07 04:26:45.
Add add_include to Serializer

Change History

09/25/07 16:14:17 changed by chuyeow

  • attachment add_includes_to_to_json.diff added.

Add :includes option to ActiveRecord#to_json

09/25/07 16:16:38 changed by chuyeow

  • attachment add_includes_to_to_json.2.diff added.

Add :includes option to ActiveRecord#to_json

09/25/07 16:19:22 changed by chuyeow

Please ignore the first diff (use add_includes_to_to_json.2.diff ).

Also forgot to mention that the JsonSerializationTest revealed a bug with the :methods option in Serializer where

method_attributes << :name if @record.respond_to?(name.to_s) 

Should be:

method_attributes << name if @record.respond_to?(name.to_s)

09/25/07 18:54:14 changed by david

This looks good, but let's abstract the commonalities between add_include in the json and xml serializers and put them in the super class. Perhaps it can just yield at the case statement or something.

09/26/07 04:26:45 changed by chuyeow

  • attachment add_includes_to_serializer.diff added.

Add add_include to Serializer

09/26/07 04:28:50 changed by chuyeow

Good point that duplication in add_includes did bother me. Please try the add_includes_to_serializer.diff patch.

I've moved add_includes up into Serializer and changed XmlSerializer accordingly. (Cleaned up some whitespace along the way.)

09/27/07 18:26:47 changed by david

  • keywords changed from ActiveRecord, JSON to ActiveRecord, JSON rails2.
  • milestone deleted.

09/27/07 21:34:58 changed by josh

Tested add_includes_to_serializer.diff. Looks good.

+1

09/28/07 14:07:26 changed by david

  • status changed from new to closed.
  • resolution set to fixed.

(In [7663]) Added :include option to to_json (closes #9677) [chuyeow]