我有一个导出 JSON 的 Rails API,类似于
# /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 ) 具有 Resource models: Customer
,Contract
并且County
都连接到该 API。当我 fetchCustomer.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