我似乎无法从我的 api 调用中捕获 nil 响应,当没有结果时我收到此错误
undefined method `[]' for nil:NilClass
因此,如果发生这种情况,我想显示一条消息,例如“找不到书”,所以我尝试了这些
<% if @results.empty? %>
<% if @results.nil? %>
<% if @results.nil %>
但他们都没有捕捉到错误
控制器
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
看法
<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>
关于它可能是什么的任何想法
谢谢