Ruby on rails 包括;“类型”;json中的属性使用Rails 3.1进行响应
当从Rails3.1应用程序返回一个包含JSON“type”属性的对象时,似乎不包括“type”属性。假设我有以下几点: 具有相应STI表动物的模型。 为猫、狗和鱼做遗传动物的模型 通过JSON返回动物时,我希望包含“type”列,但这不会发生:Ruby on rails 包括;“类型”;json中的属性使用Rails 3.1进行响应,ruby-on-rails,json,respond-with,Ruby On Rails,Json,Respond With,当从Rails3.1应用程序返回一个包含JSON“type”属性的对象时,似乎不包括“type”属性。假设我有以下几点: 具有相应STI表动物的模型。 为猫、狗和鱼做遗传动物的模型 通过JSON返回动物时,我希望包含“type”列,但这不会发生: jQuery.ajax("http://localhost:3001/animals/1", {dataType: "json"}); 收益率: responseText: "{"can_swim":false,"created_at":"2012-
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}"
有人知道这种行为背后的原因,以及如何覆盖它吗?覆盖该方法。使用它来生成输出。您可以执行以下操作:
def as_json options={}
{
id: id,
can_swim: can_swim,
type: type
}
end
对我来说,在Rails 2.3.12中,上述内容不起作用
我可以(当然是在我的模型中)这样做:
class Registration < ActiveRecord::Base
def as_json(options={})
super(options.merge(:include => [:type]))
end
end
NoMethodError: undefined method `serializable_hash' for "Registration":String
我已经用这个解决了这个问题,它将这个方法冲压到我想要导出的对象上
class Registration < ActiveRecord::Base
def as_json(options={})
super(options.merge(:include => [:type]))
end
def type
r = self.attributes["type"]
def r.serializable_hash(arg)
self
end
r
end
end
现在在我的模型类中,我添加了:
下面是我的解决方案,它可以保留as_json的原始特性
def as_json(options={})
options = options.try(:clone) || {}
options[:methods] = Array(options[:methods]).map { |n| n.to_sym }
options[:methods] |= [:type]
super(options)
end
这就是我所做的。它只是将缺少的类型
添加到结果集中
def as_json(options={})
super(options.merge({:methods => :type}))
end
这似乎是减少冗余的一个很好的折衷方案:def as_json(options={}){type:type}。我喜欢重写为_json,因为我知道如何将我的对象转换为json,并且只转换我真正需要转换的内容。
def as_json(options={})
options = options.try(:clone) || {}
options[:methods] = Array(options[:methods]).map { |n| n.to_sym }
options[:methods] |= [:type]
super(options)
end
def as_json(options={})
super(options.merge({:methods => :type}))
end