Here is my code in the view: show.html.erb
<ul>
<% @bullets.each do |r| %>
<li><%= r.content %></li>
<% end %>
</ul>
Here is my code in the controller: 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
This returns undefined method 'each' for nil:NilClass on
<% @bullets.each do |r| %>
I would like to know why it does this, and how can I fix it to post four random fixed bullet contents from a database (sqlite3) table named "bullets" (column is content).
EDIT: This is the ENTIRE controller:
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
EDIT #2: Like so?
#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