Cameron Bass Cameron Bass - 5 months ago 25
Ruby Question

undefined method `each' for nil:NilClass - Rails

I getting a nil class error. I understand exactly what this error is telling me but I don't know why it's nil. It seems to me that there should be an object getting passed to my table. This should be easy to debug. Here is my code for clarity.


def info
@subscriber = Subscriber.find_by_phone_number(params[:phone_number])


<% @subscriber.each do |subscriber| %>
<td><%= image_tag avatar_url(subscriber) %></td>
<% end %>


Showing /Users/intern/Desktop/Rails/rowster/app/views/subscribers/info.html.erb where line #3 raised:
undefined method `each' for nil:NilClass

Binding on info method:

[1] pry(#<SubscribersController>)> @subscriber
=> nil

let me know if you need anymore info?


You have two issues here:

First: @subscriber.each fails with undefined method 'each' for nil:NilClass. This basically tells you that you try to calleachin something that isnil, therefore@subscribermust benil. That meansSubscriber.find_by_phone_number(params[:phone_number])` didn't return a subscriber. The phone number send to the server doesn't have a matching entry in the database.

Second: Even if there were a matching entry in the database, your code would fail. Because find_by_phone_number would return one subscriber and not an array. Therefore calling each would fail again.

To solve both issues change your code to:

<% if @subscriber %>
    <td><%= image_tag avatar_url(@subscriber) %></td>
<% end %>
  <tr><td>No subscriber found!</td></tr>
<% end %>

And use a phone number that is in the database.