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.
@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
 pry(#<SubscribersController>)> @subscriber
You have two issues here:
@subscriber.each fails with
undefined method 'each' for nil:NilClass. This basically tells you that you try to calleach
in something that isnil
. 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 %> <tr> <td><%= image_tag avatar_url(@subscriber) %></td> </tr> <% end %> <tr><td>No subscriber found!</td></tr> <% end %>
And use a phone number that is in the database.