Instance variable problem


#1

I’m having some trouble with an instance variable being read as nil in
my app. I have an image uploading, that can be added to categories.
The page loads up initially fine, and if I upload an image without
errors everything works fine. I’m working on the validation, but with
the code I have if their are validation errors it renders ‘new’ again,
but reads @categories as nil and errors out.

In render :action => ‘new’, does it just render the template or should I
have the instance variable as well also? I’ve tried changing it to
redirect_to and it doesn’t error, but also doesn’t provide the error
messages I want.

I’ve got this in my ImageController:

def new
@categories = Category.find(:all)
end

def create
if request.post?
@image = Image.new(params[:image])
@image.categories = Category.find(params[:category_ids]) if
params[:category_ids]
if @image.save
redirect_to :action => ‘list’
flash[:notice] = ‘Image was successfully uploaded.’
else
render :action => ‘new’
end
end
end

And this code in the view gets the error:

Add Image to the Following Categories

<% for category in @categories %>  <%=category.name%>
<% end %>

And the 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.each

Extracted source (around line #21):

18:
19:


20:

Add Image to the Following Categories


21: <% for category in @categories %>

#2

Jason,

When you call render :action => ‘new’ from your create action,
there’s no @categories variable set. You either need to do:

@categories = Category.find(:all)
render :action => ‘new’

or, probably better:

new
render :action => ‘new’

Pete Y.
http://9cays.com/


#3

Pete Y. wrote:

Jason,

When you call render :action => ‘new’ from your create action,
there’s no @categories variable set. You either need to do:

@categories = Category.find(:all)
render :action => ‘new’

or, probably better:

new
render :action => ‘new’

Pete Y.
http://9cays.com/

Cheers,

I guess what confused me is I thought render :action => ‘new’ was a call
to the function. But it’s just rendering the template I see…


#4

Try doing this: " render :action => ‘new’, :locals => {:categories
=>
@categories} " , where @categories = Category.find(:all) or what
u
want.
In your view u can access categories in this way: " for category in
categories ".
Good luck…hope it works