在帶有Postgres數據庫的我的Rails 5應用程序中,我有一個名爲comments的jsonb列的模型Post。評論的默認值是{}。
比方說,這是你的表:
CREATE TABLE Posts
(
post_id SERIAL PRIMARY KEY,
comments jsonb DEFAULT '{}' /* or json instead of jsonb */
) ;
...一些示例數據
INSERT INTO Posts
(comments)
VALUES
('{"something": "a comment"}'),
('[{"something": "a comment"}, {"something":"another comment"}]'),
(DEFAULT),
('{}'),
(DEFAULT),
(NULL) ;
...看起來像:
SELECT * FROM Posts;
post_id | comments
------: | :-------------------------------------------------------------
1 | {"something": "a comment"}
2 | [{"something": "a comment"}, {"something": "another comment"}]
3 | {}
4 | {}
5 | {}
6 | null
我想返回具有評論默認值的帖子的數量。
這是因爲comments
列(平等)與{}
比較簡單:
SELECT
count(*)
FROM
posts
WHERE
comments = '{}' /* or '{}'::jsonb */
| count |
| ----: |
| 3 |
dbfiddle here
我猜(我有沒有試過)是你把它翻譯成軌道:
Post.where("comments = ?", {}.to_json).count