我有一个jbuilder来显示我的对象。
这看起来如何(部分)
o = @property_object
json.features o.property_object_feature_pack, :pool, :garage, terrace
这显示我下一步:
{
features: {
pool: {
params: null,
present: "false"
},
garage_parking: {
params: null,
present: "false"
},
terrace_balcony: {
params: null,
present: "true"
}
}
}
问题是我不希望在输出功能中显示 present:“false”。为了解决这个问题,我编写了下一个代码
json.features o.property_object_feature_pack, :pool if o.property_object_feature_pack.pool['present'] === "true"
json.features o.property_object_feature_pack, :garage_parking if o.property_object_feature_pack.garage_parking['present'] === "true"
json.features o.property_object_feature_pack, :terrace_balcony if o.property_object_feature_pack.terrace_balcony['present'] === "true"
它有效 - 但看起来很糟糕。怎么可以重构?
下一个问题是它可能是将来在ActiveRecord中添加的新功能,我想知道我们可以在不设置名称的情况下迭代o.property_object_feature_pack吗? (:pool,:garage_parking等..)
ps。 raw o.property_object_feature_pack
features: {
id: 820,
property_object_id: 56879,
created_at: "2015-04-27T18:25:25.712Z",
updated_at: "2015-04-27T18:25:25.712Z",
pool: {
params: null,
present: "false"
},
garage_parking: {
params: null,
present: "false"
},
terrace_balcony: {
params: null,
present: "true"
},
av_apartments: {
params: null,
present: "false"
}
}
更新
受#mudasobwa的启发,我创建了一个解决我问题的小助手方法
def features_list
@property_object.property_object_feature_pack.as_json.select! do |_, v|
v.is_a?(Hash) && v['present'] == 'true'
end
end
答案 0 :(得分:0)
我不知道jbuilder
是什么,但我建议将json转换为普通的ruby哈希,做任何你想做的事情并将其转换回json:
require 'json'
hash = JSON.parse what_you_got_from_builder
hash[:features].select! do |_, v|
!v.is_a?(Hash) || v[:present] == 'true'
end
hash.to_json