views:

1114

answers:

1

Hello.

I'm trying to create a registration form with Rails. It's working, but it doesn't displays the errors from the validation (it validates, but the errors don't display).

Here are my files:

# new.html.erb
<h1>New user</h1>

<% form_for :user, :url =>{:action=>"new", :controller=>"users"} do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

<%= link_to 'Back', users_path %>


# user.rb
class User < ActiveRecord::Base
    validates_presence_of :name
    validates_presence_of :password
end


#users_controller.rb
class UsersController < ApplicationController

    def index
        @users = User.all
    end


    def show
     @user = User.find(params[:id])
    end

    def new
     if session[:user_id].nil?   
      if params[:user].nil? #User hasn't filled the form
       @user = User.new
      else #User has filled the form
       user = User.new(params[:user])

       if user.save
        user.salt = rand(1000000000)
        user.password = Digest::MD5.hexdigest(user.salt.to_s + user.password)
        user.save
        flash[:notice] = 'User was successfully created.'
        session[:user_id] = user.id
        session[:password] = user.password
        redirect_to url_for(:action=>"index",:controller=>"users")
       else
        render :action=>"new"
       end
      end

     else #User is already logged in
      flash[:notice] = 'You are already registered.'
      redirect_to url_for(:action=>"index")
     end
     end 

# some other actions removed....


end


Why aren't the errors being displayed?

Thanks!!

+5  A: 

Your form POST action should really point to the create method, the new method is really just to render the form. I mean its beside the point of your problem, but it is Rails convention.

The answer to your question is that in the branch where you try and save the user you need to have your User object be an INSTANCE variable. You just have it as a local variable. So when the form renders the form helper looks in the current scope for an instance variable "@user" but it doesnt exist. Put an "@" in front of your user variable in the 2nd part of your branch where you try and do the save. If it fails then the form helper should display the errors.

Cody Caughlan
Thanks!!! Fixed...
Gabriel Bianconi