Jump To Content

LearnHub




Action Controller: Verification

Verification

Verifications make sure certain criterias are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is pres ent in the `params`, `session` or `flash` hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when the se criterias are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash me ssages and HTTP headers to the response. It is described in the API codumentation as "essentially a special kind of before_filter".

Let's see how we can use verification to make sure the user supplies a username and a password in order to log in:


class LoginsController < ApplicationController

  verify :params => [:username, :password],
         :render => {:action => "new"},
         :add_flash => {:error => "Username and password required to log in"}

  def create
    @user = User.authenticate(params[:username], params[:password])
    if @user
      flash[:notice] = "You're logged in" 
      redirect_to root_url
    else
      render :action => "new" 
    end
  end

end

Now the `create` action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for every action in LoginsController, which is not what we want. Y ou can limit which actions it will be used for with the `:only` and `:except` options just like a filter:


class LoginsController < ApplicationController

  verify :params => [:username, :password],
         :render => {:action => "new"},
         :add_flash => {:error => "Username and password required to log in"},
         :only => :create #Only run this verification for the "create" action

end

Articles in this guide

  1. Introduction
  2. What does a controller do?
  3. Parameters
  4. Sessions
  5. Cookies
  6. Filters
  7. Verification (This article)
  8. The request and response objects
  9. HTTP Basic Authentication
  10. Streaming and file downloads
  11. Parameter filtering
  12. Rescue

Thanks to the Ruby on Rails documentation team

This guide was written by Tore Darrell as part of the Ruby on Rails Documentation Project and is provided freely under a Creative Commons licence


Your Comment
Textile is Enabled (View Reference)