代码之家  ›  专栏  ›  技术社区  ›  Boucherie

从Rails控制台更新json对象

  •  0
  • Boucherie  · 技术社区  · 6 年前

    irb(main):001:0> account = Account.find(1);
    irb(main):002:0* subscription = account.subscription
    [■]   Account Load (2.2ms)  SELECT  "accounts".* FROM "accounts" WHERE "accounts"."deleted_at" IS NULL AND "accounts"."id" = $1 LIMIT 1  [["id", 1]]
    => #<Stripe::Subscription:0x35fbed4 id=sub_CPQps6J7nkb2hL> JSON: {
      "id": "jhlakdjfhbjbf",
      "object": "subscription",
    
      "default_tax_rates": [
    
      ],
      "discount": null,
      "ended_at": null,
      "livemode": true,
      "metadata": {},
      "pending_setup_intent": null,
      "plan": {"id":"free-monthly","object":"plan","active":true,...},
      "quantity": 1,
      "schedule": null,
    }
    irb(main):003:0> plan = subscription.plan
    => #<Stripe::Plan:0x35b9994 id=free-monthly> JSON: {
      "id": "tier-1",
      "object": "plan",
      "active": true,
      "aggregate_usage": null,
      "amount": 0,
      "billing_scheme": "per_unit",
      "created": 1491333713,
      "currency": "usd",
      "interval": "month"
    }
    

    当我尝试更新 plan plan.update!(id:"tier-0") 为了我的 account ?

    1 回复  |  直到 6 年前
        1
  •  0
  •   quyetdc    6 年前

    解决方法是将其转换为散列对象。然后,更新它的值,然后将其转换回原来的值(如果需要,但是,我认为您可能需要对这个对象做更多的操作)

    想想这个 question

    require 'json'
    
    
    plan = JSON.parse(subscription.plan) # Now, plan is a hash
    plan[:id] = 'tier-0'
    
    
        2
  •  0
  •   Dyaniyal Wilson    6 年前

    这将用所需的键值对更新json列,同时保持其余键不变。

    account = Account.find(1)
    plan = account.subscription['plan']
    plan = {'plan' => plan.merge(id: "tier-0") }
    account.update_attribute(:subscription, account.subscription.deep_merge(plan))