Ruby on rails 解析Rails JSON关联对象

Ruby on rails 解析Rails JSON关联对象,ruby-on-rails,Ruby On Rails,我有一个导出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.

我有一个导出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)具有资源模型:
Customer
Contract
country
都连接到该API。当我获取
Customer.find(1)
时,它似乎会根据原始类是否已加载,将相关对象解析为两个不同的类

考虑:

rails console
c = Customer.find 1
#<Customer:0x0... @attributes={"id"=>1, "county"=>#<County:0x0...>,
"contracts"=>[#<Customer::Contract:0x0...> ....
但如果我启动新控制台,在Rails加载类之前,它会变成:

reload!
c = Customer.find 1
#<Customer:0x0... @attributes={"id"=>1, "county"=>#<Customer::County:0x0...>,
"contracts"=>[#<Customer::Contract:0x0...> ....
rails console
County.new
Contract.new
c = Customer.find 1
#<Customer:0x0... @attributes={"id"=>1, "county"=>#<Customer::County:0x0...>,
"contracts"=>[#<Contract:0x0...> ....
rails控制台 新县 新合同 c=客户。查找1 #1,“县”=>#, “合同”=>。。。。 有没有办法让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
#app/models/contract.rb
类协定
通读一遍,答案是我开始怀疑-Rails检查是否已经定义了具有关联名称的类,或者是否创建了一个简单的
ActiveResource::Base
子类本身

无论是否加载了任何模型,为了使我的应用程序保持一致,我强制在initializer中加载我的所有资源模型:

[Customer, Contract, County].map &:new

顺便说一句,由于某种原因,中提到的急于加载给我带来了Factory Girl的问题。

我敢打赌这与您的模型是如何定义的有关。您的
合同是以文件夹命名的,还是以客户为子类?发布模型的代码及其目录结构可能会有所帮助。