Hello. I’m trying to create a form. It has only a username and a
password field.
The validation methods, such as validates_presence_of, aren’t working.
Does anyone know why?
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 non-related methods removed…
end
ActionController::Routing::Routes.draw do |map|
map.connect ‘login/’, :controller => “users”, :action => “login”
map.connect ‘logout/’, :controller => “users”, :action => “logout”
map.connect ‘register/’, :controller => “users”, :action => “new”
map.resources :users # I want to remove this line in the future…
map.connect ‘:controller/:action/:id’ # I want to remove this line
in the future…
map.connect ‘:controller/:action/:id.:format’ # I want to remove
this line in the future…
end
New user
<% form_for :user, :url =>{:action=>“new”, :controller=>“users”} do |
f| %>
<%= f.error_messages %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit 'Create' %>
<% end %><%= link_to ‘Back’, users_path %>
class User < ActiveRecord::Base
validates_presence_of :name, :password
end