I seem to be unable to capture a nil response from my api call, when there are no results I get this error
undefined method `[]' for nil:NilClass
So if this happens I would like to show a message like ‘No book found’, so i have tried these
<% if @results.empty? %>
<% if @results.nil? %>
<% if @results.nil %>
but none of them capture the error
Controller
def results
results = book_search(params[:search])
@results = results
@book = Book.new
@book.author = results.first["artistName"]
@book.bookname = results.first["trackName"]
@book.image = results.first["artworkUrl100"].gsub("100x100-75.jpg", "200x200-75.jpg")
@book.description = results.first["description"]
end
View
<div class="container">
<div class="row">
<div class="span8 offset2">
<% if @results.nil? %>
<h1 class="resultTitle">sorry we can't find anything for that book.</h1>
<%= link_to "Back To Search", root_path, :class => 'backButton' %>
<% end %>
<%= @results.first["trackName"] %> <br>
<img src =<%= @results.first["artworkUrl100"] %>> <br>
<%= @results.first["artistName"] %> <br>
<%= truncate(remove_tags(@results.first["description"]), :length => 250) %> <br>
<%= form_for @book do |f| %>
<%= f.label :category_id, "Category" %>
<%= f.collection_select(:category_id, Category.all, :id, :name, :prompt => 'Please select a Category') %>
<%= f.hidden_field :author %>
<%= f.hidden_field :bookname %>
<%= f.hidden_field :image %>
<%= f.hidden_field :description %>
<%= f.submit 'Save book' %>
<% end %>
</div>
</div>
</div>
Any ideas on what it could be
Thanks
The latter version will return true if
@resultsis nil. You have some other error elsewhere.If the error still shows up, then you access results even when
@results.nil?returns true. More specifically take a look at the places where you call the square bracket operator[]as the error is caused by one of them.EDIT: after discussion in chat we have discovered the problem. First in the conroller book_search returns an empty array and then, when invoking
results.first["artistName"]this causes the error, because results.first is nil. So to fix that we added the following to the controller:I.e. a check to only create a new book and set its properties if a book was found. Now in the view, a check should be added to only render the rest of the view(the part that invokes
[]operator on@resultsif results is not empty. This is achieved using an else statement:So I have added an else and an end that I have indicated in the code. Why do you need to do that? Well because even after performing the check and displaying the message, the rest of the page was still evaluated and this bit:
%= @results.first["trackName"] %> <br>was causing the error. You should not try to call the[]operator if you know@resultsis empty. The new version only displays the remaining part of the page in the else case i.e. if@resultsis not empty.Hope this makes it clear.