2017-08-04 62 views
0

在帶有Postgres數據庫的Rails 5應用程序中,我有一個型號爲Postjsonb列,名稱爲commentscomments的默認值是{}在Rails 5和PostgreSQL中查詢jsonb列的完全匹配

我想返回默認值爲comments的計數posts

當我運行​​時,我得到了Post表中每條記錄的計數。

是否有隻會返回完全匹配的查詢,所以我可以知道沒有評論的posts的數量?

回答

0

在帶有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 
相關問題