0
我有一个Rails的API出口JSON类似解析Rails的JSON关联对象
# /customers/1.json
{
"id":1,
"name":"Some name","address":"Street 12-3",
"county":{"id":2,"name":"MyCounty"},
"contracts":[
{"id":2663,"number":"6-2/7 (2011)", "county":{"id":2,"name":"MyCounty"}},
}
客户端的Rails(3.2.2)具有资源模型:Customer
,Contract
和County
所有连接到该API。当我获取Customer.find(1)
时,它似乎根据原始类是否已加载将关联对象解析为两个不同的类。
考虑:
rails console
c = Customer.find 1
#<Customer:0x0... @attributes={"id"=>1, "county"=>#<County:0x0...>,
"contracts"=>[#<Customer::Contract:0x0...> ....
注:关联类的名称:County
和Customer::Contract
现在,如果我重装控制台,就变成:
reload!
c = Customer.find 1
#<Customer:0x0... @attributes={"id"=>1, "county"=>#<Customer::County:0x0...>,
"contracts"=>[#<Customer::Contract:0x0...> ....
但是,如果我开始新的控制台,并在任何使Rails加载类之前,它变成:
rails console
County.new
Contract.new
c = Customer.find 1
#<Customer:0x0... @attributes={"id"=>1, "county"=>#<Customer::County:0x0...>,
"contracts"=>[#<Contract:0x0...> ....
有什么办法让Rails 总是用解析这些吗?
编辑:代码示例:
# app/models/contract.rb
class Contract < ActiveResource::Base
self.site = APP_CONFIG['k2api']
self.format = :json
end
# app/models/customer.rb
class Customer < ActiveResource::Base
self.site = APP_CONFIG['k2api']
self.format = :json
# accessor to ActiveResource response headers
add_response_method :http_response
end
# app/models/county.rb
class County < ActiveResource::Base
self.site = APP_CONFIG['k2api']
self.format = :json
end
我敢打赌,这与你的模型如何定义有关。您的“合同”模型是否名称空间存放在一个文件夹中,或者是否分类到客户?发布模型的代码及其目录结构可能会有所帮助。 – Veraticus 2012-08-16 15:26:50