2017-09-26 77 views
0

我目前正在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] 

回答

1

你應該瞭解的第一件事情是,如果他們沒有被設置實例變量返回nil。如果你說@fake_var == nil這將是真實的,如果你在此之前從未定義@fake_var。您可以將其與常規局部變量進行對比,如果您嘗試在定義之前使用它們,則會引發NoMethodError。例如,puts(fake_var)將引發fake_var的NoMethodError。

現在看看你的模板。不管它會循環通過@customers。如果尚未設置@customers,則會看到一個NoMethodError,因爲您無法通過nil撥打each

最後,看看你的控制器動作:

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 

具體的時params[:keywords].present?情況。在這種情況下,您從未設置@customers,因此當模板試圖訪問它時,它將爲nil

我想如果你只是用替換它會解決你的問題。

0

您可以強制其使用#to_a它轉換零到空數組陣列返回

def index 
    return [] unless params[:keywords] 
    @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 
).to_a 
end 

https://apidock.com/ruby/Array/to_a

相關問題