【发布时间】:2015-05-07 14:55:26
【问题描述】:
我有一个 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.原始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
【问题讨论】:
标签: ruby-on-rails ruby jbuilder