ruby on rails - How to write this query using active record query interface? -
i have products
table jsonb type specs
column. 1 of keys in json brand
.
i can run query this:
select specs ->> 'brand' brand, count(*) products group brand;
brand | count -------------+------- acer | 9 dell | 4 xps 15 | 1 apple | 1 lenovo | 2 gigabyte | 1 eluktronics | 5 asus | 2 hp | 1
how can run query using active record query interface?
i tried like:
product.select("specs ->> 'brand' brand").group('brand').count
not work , get:
activerecord::statementinvalid: pg::syntaxerror: error: syntax error @ or near "as" line 1: select count(specs ->> 'brand' brand) count_specs_bran... ^ : select count(specs ->> 'brand' brand) count_specs_brand_as_brand, brand brand "products" group brand (irb):1
the following should work , sticks more closely active record orm query interface:
product.all.group("specs ->> 'brand'").count
you should not include alias as brand
; active record give own alias can view in rails console
after trying out statement.
Comments
Post a Comment