這是我的視圖中的代碼:show.html.erb返回未定義的方法'each'for nil:NilClass?
<ul>
<% @bullets.each do |r| %>
<li><%= r.content %></li>
<% end %>
</ul>
這是我的代碼中,所述控制器:users_controller.rb
if cookies[:bullets].nil?
@bullets = Bullet.all.shuffle.first(4)
cookies[:bullets] = @bullets.collect(&:id)
else
@bullets = []
cookies[:bullets].each do |id|
@bullets << Bullet.find(id)
end
end
這將返回未定義的方法「各自」的零: NilClass上
<% @bullets.each do |r| %>
我想知道爲什麼它這樣做,我怎麼能解決這個問題,從命名數據庫(sqlite3的)表發佈4項隨機固定子彈內容「子彈」(列是內容)。
編輯:這是整個控制器:
class StudentsController < ApplicationController
#GET/
def index
@students = Student.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @students }
end
end
#GET /new
def new
@student = Student.new
end
#POST
def create
@student = Student.new(params[:student])
if @student.save
render :file => 'app/views/success'
else
render :file => 'app/views/students/fail'
end
end
#GET /students/{:id}
def show
@student = Student.find_by_url(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @student }
end
end
#BULLETS Randomizing /students/new.html.erb
if cookies[:bullets].nil?
@bullets = Bullet.all.shuffle.first(4)
cookies[:bullets] = @bullets.collect(&:id)
else
@bullets = []
cookies[:bullets].each do |id|
@bullets << Bullet.find(id)
end
end
#GET /students/1/edit
def edit
@student = Student.find_by_url(params[:id])
end
def update
@student = Student.find_by_url(params[:id])
respond_to do |format|
if @student.update_attributes(params[:student])
format.html { redirect_to @student, notice: 'Student was successfully updated.'}
else
format.html { render action: "edit" }
format.json { render json: @student.errors, status: :unprocessable_entity }
end
end
end
#DELETE
def destroy
@student = Student.find_by_url(params[:id])
@student.destroy
respond_to do |format|
format.html { redirect_to students_url }
format.json { head :no_content }
end
end
end
編輯#2:像這樣嗎?
#GET /students/{:id}
def show
@student = Student.find_by_url(params[:id])
#BULLETS Randomizing /students/show.html.erb
if cookies[:bullets].nil?
@bullets = Bullet.all.shuffle.first(4)
cookies[:bullets] = @bullets.collect(&:id)
else
@bullets = []
cookies[:bullets].each do |id|
@bullets << Bullet.find(id)
end
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: @student }
end
end
你確定'子彈'表不是空的? – 2012-07-06 03:05:36
150%肯定它不是空的。 編輯:它包含8個具有ID,名稱,內容和時間戳的項目符號。 – Evan 2012-07-06 03:09:06
即使該表爲空,當Array#first返回一個空數組(而不是nil)時,它會收到一個整數參數,並且明確地將'@ bullets'初始化爲'if'語句另一分支中的數組。您的控制器操作或視圖中是否還有其他事情發生,您可以發佈? – Brandan 2012-07-06 03:12:37