Reputation: 576
In my Rails application, I have a class Bar
and a controller FooController
.
class Bar
attr_accessor :id
end
class FooController < ApplicationController
def index
@rows = {}
bar = Bar.new
bar.id = 1
@rows[0] = bar
render "index"
end
end
In the view, I would like to render like this
<table>
<% @rows.each do |bar| %>
<tr>
<td><%= bar.id %></td>
</tr>
<% end %>
</table>
But it will throws error
undefined method `id' for [0, #<Bar:0x00007fc65db33320 @id=1>]:Array
If I render like this:
<%= @rows %>
the raw data of the array @rows
will be rendered as:
{0=>#<Bar:0x00007fc65db33320 @id="1">}
How do I render the elements one by one?
Upvotes: 0
Views: 1310
Reputation: 106782
The problem is that @rows = {}
doesn't assign an array but a hash. And therefore @rows[0] = bar
doesn't store bar
as the first element in the array, but it stores bar
under the key in the hash.
Just change your controller method to:
def index
@rows = []
bar = Bar.new
bar.id = 1
@rows << bar
render "index"
end
Upvotes: 1