【问题标题】:Checking values of hash before show in jbuider , Ruby on Rails在 jbuider 和 Ruby on Rails 中显示之前检查哈希值
【发布时间】: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


    【解决方案1】:

    我不知道 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
    

    【讨论】:

    • 不完全回答,但你把我推到了正确的方向。最后,我创建了一个帮手来做我需要的。 def features_list @property_object.property_object_feature_pack.as_json.select! do |_, v| v.is_a?(Hash) && v['present'] == 'true' end end
    猜你喜欢
    • 2014-04-09
    • 2017-07-09
    • 2021-12-09
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2014-07-21
    • 1970-01-01
    相关资源
    最近更新 更多