Need help: error_messages_for not working

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.

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 %>

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs