No method error - nil object


#1

I am getting following error:
##################################################
NoMethodError in TopicsController#show
You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.items
##################################################

####################

Show Method in topics controller

####################
def show
@topic = @object
@items = @topic.items
end

####################
##Topic Model
####################
class Topic < ActiveRecord::Base
validates_presence_of :title, :section_id
validates_uniqueness_of :title
has_many :items
:order => :position,
:dependent => :destroy, #don’t leave orphans (delete my children)
:conditions =>“parent_id is null” #
belongs_to :section
end

####################
##Item Model
####################

class Item < ActiveRecord::Base
validates_uniqueness_of :title, :scope => [:topic_id, :parent_id]
validates_presence_of :topic_id, :title, :owner, :position

belongs_to :topic
belongs_to :parent,
:class_name => “Item”,
:foreign_key => “parent_id”
has_many :children,
:class_name => “Item”,
:foreign_key => “parent_id”,
:order => :position,
:dependent => :destroy #don’t leave orphans (cascade delete)
has_many :attachments,
:dependent => :destroy #don’t leave orphans (cascade delete)

def section
self.topic ? self.topic.section : nil
end
end
####################

In addition, I have Items controller and attachments controller. Right
now I am starting with first Topics controller only. My config/routes.rb
file contains:
map.resources :topics
. I would like to make this application RESTful.

Any ideas on how to proceed and resolve this error?

Thanks,
CS.


#2

def show
@topic = Topic.find(params[:id])
@items = @topic.items
end
Try this method


#3

Thanks…
Well, I figured it out after I posted it on forum…
While I know why passing parameter is working, I don’t understand why
first approach didn’t work. Any clues?

Priya B. wrote:

def show
@topic = Topic.find(params[:id])
@items = @topic.items
end
Try this method


#4

You didn’t mention the id of the topic which you are trying to show…
Also where you have created @topic object?


#5

your first aproach was this:

def show
@topic = @object
@items = @topic.items
end

where would @object come from. it’s a new uninitialized variable (=
nil). that’s the reason it didn’t work.
what else did you expect than nil.items ?