0

我有一个导出 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: CustomerContract并且County都连接到该 API。当我 fetchCustomer.find(1)时,它似乎根据原始类是否已经加载,将关联的对象解析为两个不同的类。

考虑:

rails console
c = Customer.find 1
#<Customer:0x0... @attributes={"id"=>1, "county"=>#<County:0x0...>,
"contracts"=>[#<Customer::Contract:0x0...> ....

注意:关联类名称:CountyCustomer::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
4

1 回答 1

0

阅读Rails ActiveResource 源代码,答案正如我开始怀疑的那样 - Rails 检查是否已经定义了具有关联名称的类或创建了一个简单的ActiveResource::Base子类本身。

为了使我的应用程序无论是否已加载任何模型都表现一致,我在初始化程序中强制加载所有资源模型:

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

顺便说一句,由于某种原因,这个 SO 问题中提到的急切加载)给了我工厂女孩的问题。

于 2012-08-21T10:13:58.780 回答