undefined方法nil:NilClass ruby

时间:2014-04-25 16:34:26

标签: ruby-on-rails ruby

我需要做的是创建一个用户输入姓氏的页面,系统将返回与之相关的信息。我一直收到错误“未定义的方法`每个'为nil:NilClass。”我很困难,无法调试任何帮助或指导将不胜感激。

输入页面的代码

<%= 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 />

3 个答案:

答案 0 :(得分:2)

您收到错误undefined method 'each' for nil:NilClass,因为您忘记设置实例变量@customer_list的值。因此,@customer_listnil

您需要在与视图相对应的操作中设置@customer_list变量,在您呈现bookout的情况下,bookout.html.erb操作为BookinController#bookout

只需在 def bookout ## ... @customer_list = Customer.all ## Add this end 中执行此操作:

bookout

<强>更新

根据聊天讨论,OP需要显示最后一个(来自客户表),房间级别(来自苹果表),成本(来自费率表)

建议修改

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 %> 如下:

apple_id

此外,OP的架构不正确以实现此结果。已将bookings添加到rate_id表格,并从中删除了rates

注意:由于您不希望预订与rate_id表相关联,因此bookings表格中已移除cost。您必须在apples表中添加{{1}}字段才能在视图中显示费用。

答案 1 :(得分:0)

在控制器中添加此项。它将带来所有客户的详细信息。

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>

答案 2 :(得分:0)

@customer_list未定义

在控制器中定义它

@customer_list = Customer.all