I have two classes, Foo and Bar. Foo has_many Bars. Bar is actually the superclass of several classes that are sharing a STI table.
I want to make a dump of my Foo records including their associated Bars. To do this I call
Foo.all.to_json(:incude => :bars)
The initial problem is that I want to be able to distinguish between the different kinds of Bar classes. Rails makes this distinction via the type column in the Bar table, but that column isn’t included in the json serialization of the Ber records.
So, I overrode to_json in the Bar class to include the type attribute. when I call to_json on an instance of Bar, I get the new results, but when I call to_json on Foo and include its Bars, I get the old to_json (i.e. without the type attribute included).
I’ve since given up on this and am going with a different approach, but I’m still curious about what’s going on here. Maybe I should be using as_json instead of to_json? I still don’t understand the different between those two methods.
I can’t replicate this. It behaves properly in my test class.
Let’s call class #1 Foo and Foo is included as an argument to Bar. In the Bar.to_json(foo), add this:
It might shed some light on the call hierarchy and also whether your instance variable is getting to_json from the right class.