Forum: Ruby on Rails Nil Object Error

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A40281231a7dfad6fcee4b9f61687509?d=identicon&s=25 Rick Mcmillin (rickm)
on 2006-03-08 08:16
I'm a complete newbie when it comes to Ruby on Rails.  I have lots of
experience in PHP, but yesterday was the first time I sat down and began
developing using Ruby on Rails (I'm impressed!).

Anyway, I'm having a problem with edit/update of records when using form
validation.  Here are my files for reference.

ticket.rb
============
class Ticket < ActiveRecord::Base
	belongs_to :agent
	belongs_to :status
	belongs_to :priority
	belongs_to :category

	validates_presence_of :employee_id, :date, :agent_id, :status_id,
:priority_id, :category_id, :summary
end


ticket_controller.rb
============
class TicketController < ApplicationController
	layout "standard-layout"
	scaffold :Ticket

	def edit
	  @ticket = Ticket.find(params[:id])
		@employees = Employee.find_all
		@agents = Agent.find_all
		@statuses = Status.find_all
		@priorities = Priority.find_all
		@categories = Category.find_all
	end

	def update
    @ticket = Ticket.find(params[:id])
    if @ticket.update_attributes(params[:ticket])
      redirect_to :action => 'show', :id => @ticket
    else
      render :action => 'edit'
    end
  end
end

Basically, my problems began when I started using validation.  If I
complete the edit form ensuring everything validates, everything works
fine.  If I complete the edit form and leave out an entry to test
validation, I get the following error:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.inject

This error appears to occur when it tries to go back to the edit view.
At the top of my edit view is a "collection_select" that uses @employees
for population.  That appears to be what it's erroring on.

It seems as if when it goes back to the edit view, it's not grabbing the
same things that it is upon first call to the edit view.

Thanks for any help that can be provided.
F59329dc91cba06600ff65c85fd3e93c?d=identicon&s=25 Anthony Green (acgreen)
on 2006-03-08 08:50
> 	def edit
>

...

>       render :action => 'edit'

> You have a nil object when you didn't expect it!

You need to pass the id back or check the assignment otherwise @ticket
is empty.

 render :action => 'edit', :id => params[:id]

or

@ticket = Ticket.find(params[:id]) if Ticket.find(params[:id])


_tony
This topic is locked and can not be replied to.