2

Getting an undefined method `each' for nil:NilClass error for

<% for movie in trailers %>
    <li>
      <article>
        <div class="photo">
          <a href="<%= movie['links'] %>"><img src="<%= movie['thumbnail'] %>" alt="Photo" class="wrap_me_white"/></a>
        </div>
        <div class="details">
          <h4 class="title"><a href="<%= movie['title'] %>"></a></h4>
        </div>
      </article>
    </li>
  <% end %>

This is using an API from rotten tomatoes which is defined and working properly for all the other areas using different APIs.

def trailers
    config = Rails.application.config
    resp = HTTParty.get("#{config.rotten_tomatoes_api_url}movies/770672122/clips.json?apikey=#{config.rotten_tomatoes_api_key}")
    movies = JSON.parse(resp.body)['movies']
end

I have checked to make sure all the fields are correct according to rotten tomatoes. I am not sure what to do next as I've I've gone through all the problems and fixes that I have used previously. I really appreciate your time, and if there is more data needed let me know and I'd be more than happy to supply it. Thanks!

MrLore
  • 3,759
  • 2
  • 28
  • 36

2 Answers2

1

For the method trailers you are sending the response JSON.parse(resp.body)['movies'] if it returns an array then the loop will works correctly. If it returns nil then you will get the error
undefined method 'each' for nil:NilClass because you are trying to iterate a nil object.

better modify the loop like this,

<% @trailers = trailers %>  
<% for movie in @trailers %>  
  <li> ... </li>  
<% end if @trailers.present? %>
Arivarasan L
  • 9,538
  • 2
  • 37
  • 47
0

Try using an instance variable in the controller action so that the view can display each of the movies:

@movies = JSON.parse(resp.body)['movies']

Then, in your view, use the each method instead of a for loop:

<% @movies.each do |movie| %>
  ...
<% end %>
jvperrin
  • 3,368
  • 1
  • 23
  • 33