在带有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