我目前正在Rails 5應用程序中工作,您可以在其中搜索名字或姓氏,並顯示該帳戶的客戶記錄。不過,我正在從搜索算法返回一個Nil對象。未定義的方法`each'for nil:NilClass在erb數組迭代中
customers_controller:
class CustomersController < ApplicationController
def index
if params[:keywords].present?
@keywords = params[:keywords]
customer_search_term = CustomerSearchTerm.new(@keywords)
@customer = Customer.where(
customer_search_term.where_clause,
customer_search_term.where_args).
order(customer_search_term.order)
else
@customers = []
end
end
end
正如你可以看到,如果沒有發現記錄是假設返回一個空數組,但返回一個無對象。
客戶/ index.html.erb
[![<header>
<h1 class="h2">Customer Search</h1>
</header>
<section class="search-form">
<%= form_for :customers, method: :get do |f| %>
<div class="input-group input-group-lg">
<%= label_tag :keywords, nil, class: "sr-only" %>
<%= text_field_tag :keywords, nil,
placeholder: "First Name, Last Name or Email Address",
class: "form-control input-lg" %>
<span class="input-group-btn">
<%= submit_tag "Find Customers", class: "btn btn-primary btn-lg" %>
</span>
</div>
<% end %>
</section>
<section class="search-results">
<header>
<h1 class="h3">Results</h1>
</header>
<table class="table table-striped">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Joined</th>
</tr>
</thead>
<tbody>
<% @customers.each do |customer| %>
<tr>
<td><%= customer.first_name %></td>
<td><%= customer.last_name %></td>
<td><%= customer.email %></td>
<td><%= l customer.created_at.to_date %></td>
</tr>
<% end %>
</tbody>
</table>
</section>][1]][1]