我正在考虑使用 Postgres 的功能,通过 activerecords 将 json 设置到列中 json handling features我想知道如何在创建诸如 {name: '', other_name: ''}
之类的表时给它一个默认值......
我也想了解如果我为列创建一个默认的 json 值,就像上面的例子,然后我填写这些值,然后在其他时间将它重置回“默认”如何看起来会这样。
最佳答案
它就像任何其他默认设置一样,一旦你修复了 json 语法:
CREATE TABLE mytable (
someothercol integer,
somecol json DEFAULT '{"name": "", "other_name": ""}'
);
如果您设置为 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)
关于ruby-on-rails - 为 json 列设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26518078/