NoMethodError - why?


#1

Getting this error when hitting update.

NoMethodError in Article#update

You have a nil object when you didn’t expect it!
You might have expected an instance of ActiveRecord::Base.
The error occured while evaluating nil.update_attributes

Source code.

def create
@article = Article.new(params[:article])
@article.user = @session[‘user’]
if @article.save
flash[:notice] = ‘article was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end

def edit
@article = Article.find_by_article_name(params[:article_name])
if @article.user != @session[‘user’]
flash[:notice] = ‘You cannot edit an article you don’t own.’
redirect_to :action => ‘show’, :id => @article
end
end

def update
@article = Article.find_by_article_name(params[:article_name])
if @article.update_attributes(params[:article])
flash[:notice] = ‘Article was successfully updated.’
redirect_to :action => ‘show’, :id => @article
else
render :action => ‘edit’
end
end


#2

Rob B. wrote:

Getting this error when hitting update.

NoMethodError in Article#update

You have a nil object when you didn’t expect it!
You might have expected an instance of ActiveRecord::Base.
The error occured while evaluating nil.update_attributes

Source code.

def create
@article = Article.new(params[:article])
@article.user = @session[‘user’]
if @article.save
flash[:notice] = ‘article was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end

def edit
@article = Article.find_by_article_name(params[:article_name])
if @article.user != @session[‘user’]
flash[:notice] = ‘You cannot edit an article you don’t own.’
redirect_to :action => ‘show’, :id => @article
end
end

def update
@article = Article.find_by_article_name(params[:article_name])
if @article.update_attributes(params[:article])
flash[:notice] = ‘Article was successfully updated.’
redirect_to :action => ‘show’, :id => @article
else
render :action => ‘edit’
end
end

@article is nil, therefore find_by_article_name didn’t find one. You
can aboid the symtom by checking for nil before calling
update_attrbutes. As for why it didn’t find one, if you’re doing things
the standard way, you probably want params[:article][:name]

Alan


#3

Alan F. wrote:

@article is nil, therefore find_by_article_name didn’t find one. You
can aboid the symtom by checking for nil before calling
update_attrbutes. As for why it didn’t find one, if you’re doing things
the standard way, you probably want params[:article][:name]

Apologies for both the vast amount of quoted text, and the poor quality
typing. It’s definitely lunchtime.