我正在开发一个当前正在使用的系统,并且出现了一个不经常使用的功能的错误。
NoMethodError in Offer_receipts#index
Showing /Users....../app/views/offer_receipts/index.html.erb where line #8 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #8):
5: <th>Patron</th>
6: <th>One Time Offer</th>
7: </tr>
8: <% for offer_receipt in @offer_receipts %>
9: <tr>
10: <td><p> popld</p></td>
11: <td><%= offer_receipt.patron_id %></td>
当前正在显示此部分渲染页面时会发生此错误:
<h2>Offers</h2>
<div id="offers">
<% if @offers.count > 0 %>
< % @offers.each do |o| %>
<%= show_one_time_offer(o, @patron) %>
<% end %>
<% else %>
<strong>There are no offers currently available</strong>
<% end %>
</div>
单击一次性优惠后,将加载此页面,这是发生错误的页面:
index.html.erb
<% title "Offer Receipts" %>
<table>
<tr>
<th>Patron</th>
<th>One Time Offer</th>
</tr>
<% for offer_receipt in @offer_receipts %>
<tr>
<td><%= offer_receipt.patron_id %></td>
<td><%= offer_receipt.one_time_offer_id %></td>
<td><%= link_to "Show", offer_receipt %></td>
<td><%= link_to "Edit", edit_offer_receipt_path(offer_receipt) %></td>
<td><%= link_to "Destroy", offer_receipt, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<p><%= link_to "New Offer Receipt", new_offer_receipt_path %></p>
这里还有另外两个文件,它们定义了 One Time Offer 收据的方法和范围
offer_receipt.rb
class OfferReceipt < ActiveRecord::Base
belongs_to :patron
belongs_to :one_time_offer
validates :patron, :presence=>true
validates :one_time_offer, :presence=>true
require 'offer_receipt_validator.rb'
validates_with OfferReceiptValidator
end
offer_receipts_controller.rb
class OfferReceiptsController < ApplicationController
def create
begin
@patron = Patron.find(params[:patron])
rescue ActiveRecord::RecordNotFound
flash[:error] = "You must provide a patron for an offer receipt"
redirect_to root_url
return
end
@offer_receipt = OfferReceipt.new(:patron_id=>params[:patron], :one_time_offer_id=>params[:one_time_offer])
if @offer_receipt.save && @patron
redirect_to @patron, :notice => "Recorded offer receipt"
else
flash[:error] = "There was a problem saving your offer receipt"
redirect_to @patron
end
end
end
还有其他 index.html.erb 文件用于列出每个循环完全相同的其他内容,并且它们工作正常。我还检查了数据库,有超过 2000 行,所以这不是问题。