Search code examples
ruby-on-railspostgresqljsonb

How to write this query using active record query interface?


I have products table with jsonb type specs column. One of the keys in this json is brand.

I can successfully run query like this:

SELECT specs ->> 'brand' AS brand, COUNT(*) FROM products GROUP BY brand;

   brand    | count
-------------+-------
 Acer        |     9
 Dell        |     4
 XPS 15      |     1
 Apple       |     1
 Lenovo      |     2
 Gigabyte    |     1
 Eluktronics |     5
 Asus        |     2
 HP          |     1

How can I run this query using active record query interface?

I tried something like:

Product.select("specs ->> 'brand' AS brand").group('brand').count but it does not work and I get:

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "AS"
LINE 1: SELECT COUNT(specs ->> 'brand' AS brand) AS count_specs_bran...
                                       ^
: SELECT COUNT(specs ->> 'brand' AS brand) AS count_specs_brand_as_brand, brand AS brand FROM "products" GROUP BY brand
        from (irb):1

Solution

  • The following should work and sticks more closely to the active record ORM query interface:

    Product.all.group("specs ->> 'brand'").count
    

    You should not include the alias AS brand; active record will give its own alias for this which you can view in the rails console after trying out this statement.