【问题标题】:Give default value to nested jsonb on Rails 4 /postgresql 9.4为 Rails 4 /postgresql 9.4 上的嵌套 jsonb 提供默认值
【发布时间】:2015-07-30 11:21:27
【问题描述】:

我希望在我的用户表上添加一个 jsonb 列(称为 per_deal_numbers)并准备迁移

class AddInfoToUsers < ActiveRecord::Migration
  def change
    add_column :users, :per_deal_numbers, :jsonb, default: '{??????}'

  end
end

例如,对于已经完成大量交易的用户来说,它看起来像这样:

user=(
id:1,
name:Eric,
age: 24,
per_deal_numbers: {
  deal1 : {"nb_of_shots"=>20, "nb_of_lost_guesses"=> 6 },
  deal10: {"nb_of_shots"=>13, "nb_of_lost_guessess"=> 4 },
  deal5: {"nb_of_shots"=>54, "nb_of_lost_guesses"=> 9 }
}

我想在我的迁移中说明:每当您为用户刚刚参与的交易插入新条目时,将 nb_of_shots 和 nb_of_lost_guesses 值设置为 0

我应该在迁移中还是稍后在我的 rails 应用程序逻辑方法 upsert 中提供这一点?

【问题讨论】:

    标签: ruby-on-rails json postgresql ruby-on-rails-4 rails-postgresql


    【解决方案1】:

    我知道这是一个较老的问题,但也许答案对任何人都有更多帮助。 对象键必须用引号括起来。

    这是一个例子:

    class CreateSettings < ActiveRecord::Migration
     def change
      create_table :settings do |t|
        t.jsonb :price_calculator, null: false, default: '{"formula": {"main_factor": 8, "city_factor": 7} }'
        t.timestamps null: false
      end
     end
    end
    

    【讨论】:

      猜你喜欢
      • 2015-02-27
      • 2016-10-25
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多