开发者

overriding as_json for as_json(:includes => :association)

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开发者_JS百科 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:

foo.class.ancestors.each do |c|
  has_json = c.instance_methods.include?(:to_json)
  p "#{c} has to_json: #{has_json}"
  if has_json
    p "Owner: #{c.instance_method(:to_json).owner}"
  end
end

It might shed some light on the call hierarchy and also whether your instance variable is getting to_json from the right class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜