0

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?

4
  • 2
    With the code you have shown, it should not be throwinng that undefined method error. Are you sure it's coming from that line? Commented Feb 14, 2019 at 9:31
  • 1
    Your example and its output don't match. According to your code (@rows[0] = bar), the "raw data" should have a key of 0, not 1. Please provide a valid example and also include the whole error message, including the error's line number. Commented Feb 14, 2019 at 9:47
  • @Stefan: Yes you are right. Sorry again. I have just corrected it in the question. Commented Feb 14, 2019 at 10:29
  • @kbisang it makes much more sense now, thanks for taking the time to edit the question! Commented Feb 14, 2019 at 11:54

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

8 Comments

Doesn't explain the "undefined method 'each' for nil:NilClass" error – hash does respond to each.
Great, that helps! Thanks Spickermann for your correct answer.
the problem was that I filled the array @rows like this @rows[0] = bar instead of @rows << bar
@kbisang I don't see how that could result in the given error message.
@kbisang what do you mean? If i have @rows = {} and @rows[0] = 'foo', then @rows.each { ... } doesn't give an error. Hashes can be traversed via each just fine (of course).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.