C
C
Chronic 862015-01-01 21:09:26
Ruby on Rails
Chronic 86, 2015-01-01 21:09:26

How to adjust the data to display a graph in a Ruby on Rails application?

Please help.
There is an ActiveRecord request

<%= pie_chart Uk.find_by_sql("SELECT uks.MEANING, SUM(OPLATA) FROM oplata o, uks WHERE o.UK_ID = uks.UK_ID GROUP BY uks.MEANING") %>

Returning the following data:
[{"meaning":"Имя1","sum(oplata)":448616,"id":null},{"meaning":"Имя 2","sum(oplata)":112154,"id":null},{"meaning":"Имя 3","sum(oplata)":224308,"id":null}]

How can the received data be converted into something like this:
{"Имя 1":448616,"Имя 2":224308,"Имя 3":112154}
Or how can I correctly write down an ActiveRecord query without SQL injection?
uk.rb
class Uk < ActiveRecord::Base
    has_many :oplata
end

oplata.rb
class Oplata < ActiveRecord::Base
    belongs_to :uks
end

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Chronic 86, 2015-01-03
@chronic86

Unfortunately, there is not enough experience, and this is probably why all attempts to run through the array with all sorts of map, each, etc. were not crowned with success. Helped apidoc and query TableName.connection.select_rows("SQL")
In the future I hope to be able to correctly rewrite this query through ActiveRecord without SQL.

S
Sworg, 2015-01-02
@Sworg

You can iterate over your resulting array and make the desired hash, as an option

A
Anton Misyagin, 2016-01-04
@sunnmas

b = a.map{|x| {x['meaning'] => x['sum(oplata)']}}
I wrote exactly how to convert the data without thinking about what it all means. Didn't check.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question