Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails-convert activeRecord to arrays

I currently have a database of compounds. For each compound, I have a series of data points, each of which consist of a time (t0, t2,t4,...,t24) and a corresponding value. I would like to extract the keys (t0, t2,t4,...,t24) and values and put them into separate arrays so I can graph them. I obtain my active record with the line:

data = Info.where('compoundName = ?',params[:cmpName])

Then I attempted to extract the keys and values using the lines:

a1 = data.keys
a2 = data.values

but I got the error:

undefined method `keys' for ActiveRecord::Relation::ActiveRecord_Relation_Info:0x007fafcdadba18

I looked this up and saw that the issue was that the sql query returned a data type that could not support these methods. But I am unsure how unpack the active record into the desired arrays. If I print out the active record it looks like this:

[#<Info num: 6, compoundName: "cmp1", t0: 78.77867, t2: 69.57333, t4: 68.95822, t6: 66.21941, t8: 65.37794, t10: 62.696, t12: 60.85907, t14: 60.40803, t16: 58.97237, t18: 59.55294, t20: 57.79256, t22: 57.17229, t24: 56.31774>]

Does anyone know how to accomplish this? Thanks!

like image 941
adub Avatar asked Dec 14 '25 02:12

adub


1 Answers

If you just want to convert the sql object into array, you can simply do this:

data = Info.where('compoundName = ?',params[:cmpName]).to_a

and it will perform the fetch.

like image 61
Edward Avatar answered Dec 16 '25 17:12

Edward