似乎当从 Rails 3.1 应用程序返回包含“类型”属性作为 JSON 的对象时,“类型”属性不包括在内。假设我有以下内容:
具有相应 STI 表 Animal 的模型。继承 Animal 的 Cat、Dog 和 Fish 模型。
通过 JSON 返回动物时,我希望包含“类型”列,但这没有发生:
jQuery.ajax("http://localhost:3001/animals/1", {dataType: "json"});
产量:
responseText: "{"can_swim":false,"created_at":"2012-01-20T17:55:16Z","id":1,"name":"Fluffy","updated_at":"2012-01-20T17:55:16Z","weight":9.0}"
这似乎是 to_json 的问题:
bash-3.2$ rails runner 'p Animal.first.to_yaml'
"--- !ruby/object:Cat\nattributes:\n id: 1\n type: Cat\n weight: 9.0\n name: Fluffy\n can_swim: false\n created_at: 2012-01-20 17:55:16.090646000 Z\n updated_at: 2012-01-20 17:55:16.090646000 Z\n"
bash-3.2$ rails runner 'p Animal.first.to_json'
"{\"can_swim\":false,\"created_at\":\"2012-01-20T17:55:16Z\",\"id\":1,\"name\":\"Fluffy\",\"updated_at\":\"2012-01-20T17:55:16Z\",\"weight\":9.0}"
有谁知道这种行为背后的原因,以及如何覆盖它?