Bitwise
Bitwise

Reputation: 8461

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.

CONTROLLER METHOD:

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

VIEW:

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

ERROR:

 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?

Upvotes: 1

Views: 2462

Answers (1)

spickermann
spickermann

Reputation: 107107

You have two issues here:

First: @subscriber.each fails with undefined method 'each' for nil:NilClass. This basically tells you that you try to call each in something that is nil, therefore @subscriber must be nil. That means Subscriber.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 %>
  <tr>
    <td><%= image_tag avatar_url(@subscriber) %></td>
  </tr>
<% else %>
  <tr><td>No subscriber found!</td></tr>
<% end %>

And use a phone number that is in the database.

Upvotes: 6

Related Questions