设置json列的默认值

See*_*uth 1 postgresql activerecord json ruby-on-rails

我正在寻找使用Postgres的功能,通过activerecords json处理功能将json设置为一列我想知道如何在表创建类似{name: '', other_name: ''}等等时给它一个默认值...

我也想了解如何为列创建默认的json值,如上面的示例,然后我填写值,但在其他时间将其重置为"默认",如何看起来.

Cra*_*ger 5

一旦你修复了json语法,它就像任何其他默认值一样:

CREATE TABLE mytable (
    someothercol integer,
    somecol json DEFAULT '{"name": "", "other_name": ""}'
);
Run Code Online (Sandbox Code Playgroud)

如果你设置为DEFAULT,那就是这样:

regress=> INSERT INTO mytable(someothercol, somecol) VALUES (42, '{"nondefault": 1}');
INSERT 0 1
regress=> SELECT * FROM mytable;
 someothercol |      somecol      
--------------+-------------------
           42 | {"nondefault": 1}
(1 row)

regress=> UPDATE mytable SET somecol = DEFAULT WHERE someothercol = 42;
UPDATE 1
regress=> SELECT * FROM mytable;
 someothercol |            somecol             
--------------+--------------------------------
           42 | {"name": "", "other_name": ""}
(1 row)
Run Code Online (Sandbox Code Playgroud)