Andrew James Andrew James - 3 months ago 16
Ruby Question

where best to calculate and create a large table to be shown in view?

Based on a couple of fields in the ActiveRecord I need to do a series of calculations which will result in displaying a table (in the View) with around 10 columns and 15 rows.

I don't want to do these calculation in the View so I thought about creating a 2D Array to store the rows in the Model and then just access this array in the View to build a table to show.
However it seems I cannot store an Array in a Model's instance variable so am looking for suggestions on how to best handle this situation?

If there is a way to pass an Array from the Model to the View this would solve my problem.
Tried something like this but didnt work due to attr_accessor not handling arrays?

Model xxx

attr_accessor :row_hash
after_initialize do
makeTable
end
def makeTable
row_hash = Array.new
for i in 1..15 do
row_hash.push(i)
end
end


View

<% @xxx.row_hash.each do |r| %>
<%= r %>
<% end %>


The row_hash populates ok in the Model but I get 'no method defined each' in the view

Answer

I think you can make it work by adding self to row_hash

attr_accessor :row_hash
after_initialize do
    makeTable
end
def makeTable
    self.row_hash = Array.new
    for i in 1..15 do
        self.row_hash.push(i)
    end
end

Initializing row_hash = Array.new will create a local variable called row_hash so you need to call self.row_hash= in order to access the instance attribute writer.

However, this is still a little odd to do in a model so there might be a better way to handle this overall.

Comments