[英]undefined method nil:NilClass ruby
我需要做的是創建一個頁面,用戶將在其中輸入姓氏,系統將返回與其相關的信息。 我不斷收到錯誤“ nil:NilClass的未定義方法'each'”。 我陷入困境,無法調試它,將不勝感激任何幫助或指導。
輸入頁面代碼
<%= form_tag(showcustcourses_custcoursesout_path, :controller => "showcustcourses", :action => "custcoursesout", :method => "post") do %>
<div class="field">
<%= label_tag :Customer_Name %><br />
<%= text_field_tag :customer_name_in %>
</div>
<div class="actions">
<%= submit_tag "Submit Customer Name" %>
</div>
<% end %>
控制器代碼
class BookinController < ApplicationController
def bookin
end
def bookout
@customer_name = params[:customer_name_in]
@r = Customer.find_by_last(@customer_name)
@rate_list = @r ? @r.rates : nil
end
end
輸出頁面的代碼( <% @customer_list.each do |m| %>
引發錯誤)
<h1>Bookin#bookout</h1>
<p>Find me in app/views/bookin/bookout.html.erb</p>
<center><table width = 65% border = 1>
<tr> <th> Customer Name</th><th> Room Number </th> <th> Cost </th></tr>
<% @customer_list.each do |m| %>
<tr> <td> <%= m.name %> </td> <td> <%= m.roomnumber %> </td> <td> <%= m.cost %> </td> </tr>
<% end %>
</table> </center><br /> <br />
您正在得到undefined method 'each' for nil:NilClass
的錯誤undefined method 'each' for nil:NilClass
因為您忘記設置實例變量@customer_list
的值。 因此, @customer_list
為nil
。
您需要在與您的視圖相對應的操作中設置@customer_list
變量,這種情況下,您在呈現bookout.html.erb
是bookout
操作。
只需在BookinController#bookout
執行以下BookinController#bookout
:
def bookout
## ...
@customer_list = Customer.all ## Add this
end
更新
根據聊天討論,OP需要顯示last(來自customers表),roomlevel(來自apples表),cost(來自rates表)
建議修改
bookout
方法如下:
def bookout
@customer_list = Customer.all
@customer_name = params[:customer_name_in]
end
和bookout.html.erb
如下:
<% @customer_list.each do |customer| %>
<% customer.bookings.each do |booking| %>
<tr>
<td> <%= customer.last %> </td>
<td> <%= booking.apple.room_level %> </td>
<td> <%= booking.apple.cost %> </td>
</tr>
<% end %>
<% end %>
此外,OP的架構也不適合實現此結果。 在bookings
表中添加了apple_id
,並從其中刪除了rate_id
。
注意:由於您不希望預訂與rates
表相關聯,因此rate_id
從bookings
表中刪除。 您必須在apples
表中添加cost
字段才能在視圖中顯示成本。
將此添加到您的控制器中。 它將帶來所有客戶的詳細信息。
def bookin
@customer_list = Customer.all
end
def bookout
@customer_list = Customer.all
@customer_name = params[:customer_name_in]
@r = Customer.find_by_last(@customer_name)
@rate_list = @r ? @r.rates : nil
end
如果仍然返回nil錯誤,則意味着您在數據庫中沒有任何客戶記錄。
<h1>Bookin#bookout</h1>
<p>Find me in app/views/bookin/bookout.html.erb</p>
<center><table width = 65% border = 1>
<tr> <th> Customer Name</th><th> Room Number </th> <th> Cost </th></tr>
#check if object is not nil
<% if !@customer_list.nil? %>
<% @customer_list.each do |m| %>
<tr>
<td> <%= m.name %> </td>
<td> <%= m.roomnumber %> </td>
<td> <%= m.cost %>
</td>
</tr>
<% end %>
<% else %>
<p> no customers available </p>
<% end %>
</table>
</center>
未定義@customer_list
像這樣在控制器中定義它
@customer_list = Customer.all
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.