# Need help: error\_messages\_for not working

**URL:** <https://www.ruby-forum.com/t/need-help-error-messages-for-not-working/88375>\
**Category:** Rails\
**Created:** [March 10, 2007, 5:23am UTC](https://www.ruby-forum.com/t/need-help-error-messages-for-not-working/88375 "2007-03-10T05:23:54Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![askme](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/d6d6ee/32.png) [@askme](https://www.ruby-forum.com/u/askme)\
**Post date:** [March 10, 2007, 5:23am UTC](https://www.ruby-forum.com/t/need-help-error-messages-for-not-working/88375/1 "2007-03-10T05:23:54Z")

</div>

Hi,

I’m a newbie to ruby on rails. While I am writing a new application,  
I bumped into the following issue.

My model is as follows:

class UserRequest \< ActiveRecord::Base

# Name can’t contain fewer than 4 chars / more than 8 chars.

validates\_length\_of :name, :within =\> 4…8, :on =\> :create  
end

If I use scaffolding, the error message is displayed as expected when  
I tried to create a record with name fewer than 4 chars. However, if I  
write an action myself, the error messages are not displayed.

class UsersController \< ApplicationController  
def new  
if request.post?  
user = UserRequest.create(:name =\> params[:name])  
flash[:notice] = “User (Name: #{user.name}) was created  
successfully”  
end  
end  
end

Here’s the view (new.rhtml)  
\<%= error\_messages\_for :user\_request %\>  
\<%= flash[:notice] %\>  
\<% form\_tag do %\>  
Please enter your name: \<%= text\_field\_tag :name, nil %\>  
\<% end %\>

The error\_messages\_for doesn’t display any error messages at all. I’m  
sure the validation was happening as the record doesn’t get added in  
the database if the input doesn’t satisfy the condition. I’ve put my  
back into debugging this for 4 whole days and finally decided to  
trouble you guys. Please let me know if I’m doing something wrong  
here. Thanks in advance.

---

<div class="post-metadata">

**Author:** ![askme](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/d6d6ee/32.png) [@askme](https://www.ruby-forum.com/u/askme)\
**Post date:** [March 10, 2007, 5:36am UTC](https://www.ruby-forum.com/t/need-help-error-messages-for-not-working/88375/2 "2007-03-10T05:36:55Z")

</div>

Woooooha! I was able to resolve this. I was using class name instead  
of instance variable in error\_messages\_for. This group is a great  
place!

Here’s the fixed code:

Fixed controller code:

class UsersController \< ApplicationController  
def new  
if request.post?  
@user = UserRequest.create(:name =\> params[:name])  
flash[:notice] = “User (Name: #{@user.name}) was created  
successfully”  
end  
end  
end

Here’s the fixed - view (new.rhtml)  
\<%= error\_messages\_for ‘user’ %\>  
\<%= flash[:notice] %\>  
\<% form\_tag do %\>  
Please enter your name: \<%= text\_field\_tag :name, nil %\>  
\<% end %\>
