views:

28

answers:

2

Hello, in an attempt to create a model with an array as an atribute, i ended up creating an array of hashes like so:

    data1 = {}
    data1[:name] = "Virtual Memory"
    data1[:data] = @jobs.total_virtual_memory
    data2 = {}
    data2[:name] = "Memory"
    data2[:data] = @jobs.total_memory
    @data = []
    @data << data1
    @data << data2

which populates @data like this:

[{:data=>[#<Job day: "2010-08-02">, #<Job day: "2010-08-04">], :name=>"Virtual Memory"}, {:data=>[#<Job day: "2010-08-02">, #<Job day: "2010-08-04">], :name=>"Memory"}]

However i do not know how to acces these variables in the view. So as tu run somethig like:

for series in @data
  series:name 
     for d in series:data
      data:[Date, Value]
     end    
end

which would return something along the lines of:

 Name1
      Date1, Value1
      Date2, Value 2,
      Date3, Value 3,
      Date4, Value 4,
  Name2 
      Date1, Value 1,
      Date2, Value 2,
      Date3, Value 3,
      Date4, Value 4,
A: 

Hello, I figured it out.

Here is the view:

<% for d in @data %>
    {   pointInterval: <%= 1.day * 1000 %>,
        name:<%= "'#{d[:name]}'"%>,
        pointStart: <%= 2.weeks.ago.at_midnight.to_i * 1000 %>,  
              data: [
            <% for chart in d[:data] %>
             <%= "'[#{chart.day.to_time(:utc).to_i * 1000}, #{chart.data_attribute}],'" %>
            <% end %>

                    ]
    },                                      
    <% end %>

Use #{d[:name]} to access the value of the "name" key and use d[:data] to access the array, then just loop throughthe array as if it were any normal array

jalagrange
+1  A: 

This should work:

<% for series in @data %>
  <%= series[:name] %>
  <% for d in series[:data] %>
    <%= d.date %>, <%= d.value %>
  <% end %>
<% end %>

However you might consider using a more suitable datastructure instead of hashs. A Struct for example. This could look like this:

# in lib/JobData.rb:
JobData = Struct.new(:name, :data)

# in the controller:
data1 = JobData.new("Virtual Memory", @jobs.total_virtual_memory)
data2 = JobData.new("Memory", @jobs.total_memory)
@data = [data1, data2]

# in the view:
<% for series in @data %>
  <%= series.name %>
  <% for d in series.data %>
    <%= d.date %>, <%= d.value %>
  <% end %>
<% end %>

As a style point: I used for because you used for, but in general it's considered more rubyish to use each instead.

sepp2k
Hello Sepp2k! Thank you very much, I will try using Struct, it certainly seems much more "rubyish"
jalagrange
Considering your view is entirely almost scriptlets, you should make a helper that outputs the HTML and call the helper from the view.
mathepic