在json respond_with Rails 3.1中包含"type"属性

cyr*_*usd 11 json ruby-on-rails respond-with

当从Rails 3.1应用程序返回包含"type"属性作为JSON的对象时,似乎不包括"type"属性.假设我有以下内容:

具有相应STI表Animal的模型.继承Animal的Cat,Dog和Fish模型.

通过JSON返回Animal时,我希望包含"type"列,但这不会发生:

jQuery.ajax("http://localhost:3001/animals/1", {dataType: "json"});
Run Code Online (Sandbox Code Playgroud)

收益率:

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}"
Run Code Online (Sandbox Code Playgroud)

看来这是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}"
Run Code Online (Sandbox Code Playgroud)

有谁知道这种行为背后的原因,以及如何覆盖它?

use*_*245 17

这就是我做的.它只是将缺失添加type到结果集中

  def as_json(options={})
    super(options.merge({:methods => :type}))
  end
Run Code Online (Sandbox Code Playgroud)


luc*_*tte 6

覆盖as_json方法.它用于to_json产生输出.你可以这样做:

def as_json options={}
 {
   id: id,
   can_swim: can_swim,
   type: type
 }
end
Run Code Online (Sandbox Code Playgroud)

  • 这似乎是减少冗余的一个很好的折衷方案:def as_json(options = {}){type:type} .merge super end (5认同)