我有以下搜索结果(json)我需要与模型联系(我扩展了第一个以使其更具可读性:
{"products_matched":
{ "89": //<-- this is a product ID
{ "lines": {
"0": {
"meta_count": 6,
"metas": {
"0": [0, 4], "1": [0, 4], "2": [0, 1], "3": [1, 2], "4": [2, 3], "5": [3, 4]
}
},
"1": {
"meta_count": 5,
"metas": {
"0": [0, 4], "1": [0, 4], "2": [0, 1], "3": [1, 2], "4": [2, 3]
}
}
},
"product_score": 0.0
} ,
"82": {"lines": {"0": {"meta_count": 2, "metas": {"0": [0, 4], "1": [0, 4]}}}, "product_score": 0.55},
"60": {"lines": {"0": {"meta_count": 3, "metas": {"0": [0, 4], "1": [0, 4], "2": [3, 4]}}}, "product_score": 0.0},
"10": {"lines": {"0": {"meta_count": 2, "metas": {"0": [0, 4], "1": [0, 4]}}}, "product_score": 0.0}}
}
在rails中,如何返回模型对象和附加到id的关联元数据(行)?
到目前为止我所拥有的:
product_ids = results["products_matched"].keys # => ["89", "82", "60", "10"]
products = Product.where(id: product_ids) # => #<ActiveRecord::Relation [#<Product id: 82, name: ...],[...] ...>
我可以尝试在一个实例变量下收集/映射它们,或者我可以单独发送它们,但是这样就可以将两者结合起来了。
答案 0 :(得分:0)
简单的解决方案,我不知道它是否是最好的,但我刚刚向attr_accessor
模型添加了Product
。
attr_accessor :result
然后我遍历产品:
product_ids = results["products_matched"].keys # => ["89", "82", "60", "10"]
@products = Product.where(id: product_ids)
@products.each do |p|
p.result = results["parsers_matched"][p.id.to_s]
end