在我的rails应用程序中,我有2个“远程模型”。这些模型不是active_record模型,而是使用API提供的gem在API上检索。
我将哈希数据发送到库中,库以哈希的形式提供数据。我的问题更多是关于如何生成正确的哈希
我的问题可以用以下2个模型来说明;
remote_user.rb
this.quoteService.getQuotes().mergeMap( quotes => {
// Do whatever you need to do with quotes
return this.quoteService.getOptions()
}).subscribe( options => {
// Do whatever you need with options
});
remote_adresse.rb
class RemoteUser
include ActiveModel::Model
include ActiveModel::Serialization
attr_accessor(
:Name
:Email
...)
end
def attributes{ 'Name'=> nil,'Email'=>nil .....}
attr_reader(:HeadquartersAdress)
def HeadquartersAddress=(data={})
if data.is_a? RemoteAdresse
@HeadquartersAddress=data
else
@HeadquartersAddress=RemoteAdresse.new(data)
end
end
测试:
class RemoteAdresse
include ActiveModel::Model
include ActiveModel::Serialization
attr_accessor(
:AddressLine1,
:AddressLine2,
:City,
:Region,
:PostalCode,
:Country
)
def attributes
{
'AddressLine1'=>nil,
'AddressLine2'=>nil,
'City'=>nil,
'Region'=>nil,
'PostalCode'=>nil,
'Country'=>nil
}
end
end
我更愿意:{“Name”=>“Foo”,“HeadquartersAddress”=> { “城市”= “新加坡”}}
嵌套对象(adresse)未序列化。我该怎么做才能使它序列化?
答案 0 :(得分:1)
如果我没有完全弄错,你需要在serializable_hash
电话中包含关联,如下所示:
test = RemoteUser.new Name: 'Foo'
test.HeadquartersAddress=RemoteAddress.new City: 'singapour'
test.serializable_hash(include: :HeadquarterAddress)
如果这不起作用,则始终可以覆盖read_attribute_for_serialization
并将其调整为HeadquarterAddress
属性。