我正在使用当前正在使用的系统,并且出现了一个不经常使用的功能的错误。
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>
以下是另外两个定义一次性优惠收据的方法和范围的文件
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行,所以这不是问题。
答案 0 :(得分:0)
您的@offer_receipt
控制器操作中未设置您的实例变量#index
。
您应该添加#index
操作。这样的事情应该有效:
class OfferReceiptsController < ApplicationController
def index
@offer_receipts = OfferReceipt.all
end
end
您还可以在#index
操作中添加其他逻辑。例如,您可能希望将实例变量的范围限定为current_user
。
@offer_receipts = OfferReceipt.where(:user_id => current_user.id)