I think there exists a bug in the ActiveRecord::Serialization.
The example below takes an Active Record Campaign object and
serializes it into JSON including its related sub_category object and
its related subscriptions object.
@campaign.to_json(:include=> {:sub_category => {:include
=> :subscriptions}})
This works perfect and returns:
{“sub_category_id”: 1, “name”: “ready campaign”, “updated_at”: null,
“thumbnail”: null, “sub_category”: {“name”: “News Alerts”,
“subscriptions”: [{“sub_category_id”: 1, “updated_at”: “2008/01/18
23:01:41 -0800”, “timestamp_start”: “2008/01/18 22:12:00 -0800”, “id”:
1, “timestamp_end”: “2008/01/18 23:01:00 -0800”, “subscriber_id”: 1,
“is_subscribed”: true, “created_at”: “2008/01/18 23:01:41 -0800”}],
“updated_at”: null, “long_text”: null, “id”: 1, “description”: null,
“category_id”: 1, “picture”: null, “created_at”: null}, “body”: “you
should send this campaign now”, “campaign_status_id”: 3, “subject”:
“this campaign is ready”, “notes”: null, “id”: 5, “billing_code”:
null, “valid_after”: null, “ad_id_source”: null, “created_at”:
“2007/08/24 16:15:16 -0700”}
Adding another relationship on the same level of sub_category works
too:
@campaign.to_json(:include=> [:sub_category, :delivery_schedule])
However, If I want to include another object on the same level as
sub_category, the serialization fails (see delivery_schedules on same
level as sub_category):
@campaign.to_json(:include=> [{:sub_category => {:include
=> :subscriptions}}, :delivery_schedule])
Returns this error:
NoMethodError (You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.macro):
/vendor/rails/activerecord/lib/active_record/serialization.rb:
55:in add_includes' /vendor/rails/activerecord/lib/active_record/serialization.rb: 54:in
each’
/vendor/rails/activerecord/lib/active_record/serialization.rb:
54:in add_includes' /vendor/rails/activerecord/lib/active_record/serialization.rb: 76:in
serializable_record’
/vendor/rails/activesupport/lib/active_support/core_ext/object/
misc.rb:28:in returning' /vendor/rails/activerecord/lib/active_record/serialization.rb: 74:in
serializable_record’
/vendor/rails/activerecord/lib/active_record/serializers/
json_serializer.rb:67:in serialize' /vendor/rails/activerecord/lib/active_record/serialization.rb: 91:in
to_s’
/vendor/rails/activerecord/lib/active_record/serializers/
json_serializer.rb:57:in `to_json’
Any ideas?