This article was excerpted from Rob Orsini's Rails Cookbook with permission of O'Reilly Media Inc., all rights reserved. Diego Scataglini wrote this particular recipe for the book.
Problem
You need to create a typical sign-up form, perhaps for a company newsletter. You want to validate all required fields as well as make sure that users accept the terms and conditions.
Solution
Creating Web forms is probably the most common task in Web development. For this example, assume you have a Rails application created with the following table:
class CreateSignups < ActiveRecord::Migration
def self.up
create_table :signups do |t|
t.column :name, :string
t.column :email, :string
t.column :dob, :date
t.column :country, :string
t.column :terms, :integer
t.column :interests, :string
t.column :created_at, :datetime
end
end
def self.down
drop_table :signups
end
end
Create a corresponding model and controller:
$ ruby script/generate model signup
$ ruby script/generate controller signups index
Now add some validations to the Signup model:
app/models/signup.rb:
class Signup < ActiveRecord::Base
validates_presence_of :name, :country
validates_uniqueness_of :email
validates_confirmation_of :email
validates_format_of :email,
:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
validates_acceptance_of :terms,
:message => "Must accept the Terms and Conditions"
serialize :interests
def validate_on_create(today = Date::today)
if dob > Date.new(today.year - 18, today.month, today.day)
errors.add("dob", "You must be at least 18 years old.")
end
end
end
Next, add the following index method to your Signups controller:
app/controllers/signups.rb:
class SignupsController < ApplicationController
def index
@signup = Signup.new(params[:signup])
@signup.save if request.post?
end
end