我想在我的用户表上添加一个 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
我应该在迁移中或稍后在 upsert 的 Rails 应用程序逻辑方法中提供此功能吗?
最佳答案
我知道这是一个较老的问题,但也许答案对任何人都有帮助。 对象键必须写在引号中。
这是一个例子:
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
关于ruby-on-rails - 为 Rails 4/postgresql 9.4 上的嵌套 jsonb 提供默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30311937/