简体   繁体   中英

Query Result into JSON in Rails

I want to store the query result for the below query

"SELECT sum( CASE WHEN properties like '%abcd%' THEN 1 ELSE 0 END) 'abcd',
        sum( CASE WHEN properties like '%gef%' THEN 1 ELSE 0 END) 'gef',
        sum( CASE WHEN properties like '%hij%' THEN 1 ELSE 0 END) 'hij',
        sum( CASE WHEN properties like '%lmn%' THEN 1 ELSE 0 END) 'lmn' from events"

as JSON in the form

{'abcd': 1, 'gef' : 2, 'hij' : 1, 'lmn' : 3} 

in Rails.

I use count_result = ActiveRecord::Base.connection.execute(sql) which returns only the values and not the keys. I get the results in the format [1,2,1,3].

How to obtain the key values and store them into json format?

Use ActiveRecord::Base.connection.exec_query to get a ActiveRecord::Result object which can be turned into a hash:

result = ActiveRecord::Base.connection.exec_query("SELECT sum( CASE WHEN properties like '%abcd%' THEN 1 ELSE 0 END) 'abcd',
        sum( CASE WHEN properties like '%gef%' THEN 1 ELSE 0 END) 'gef',
        sum( CASE WHEN properties like '%hij%' THEN 1 ELSE 0 END) 'hij',
        sum( CASE WHEN properties like '%lmn%' THEN 1 ELSE 0 END) 'lmn' from events")

result.to_h # => { 'abcd' => 1, 'hij' => 0 ... }

To convert the values to a JSON string you just call .to_json on the hash. But if you are using a native JSON column type you do not need to manually convert it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM