The controller:

<pre><code>class \WeblogController < ActionController::Base
  def show # not used directly, just example
    @post = Post.find(@params["id"])
  end

  def new
    @post = Post.new
  end
  
  def create
    @post = Post.new(@params["post"])
    if @post.save
      redirect_to :action => "show", :id => @post.id
    else
      render_action "new"
    end
  end
end
</code></pre>

The new template:

<pre><code><% unless @post.errors.empty? %>
  The post couldn't be saved due to these errors:
  <ul>
  <% @post.errors.each_full do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>
<% end %>

<%= form "post" %>
</code></pre>

or even shorter:
<pre><code>
<%= error_messages_for 'post' %>
</code></pre>

The model (0.9): 
<pre><code>class Post < ActiveRecord::Base
    validates_presence_of :title, :body, :message => "Missing required field"
    validates_length_of :title, :maximum => 10, :message => "Title too long - max 10 characters"
end</code></pre>

The model (pre 0.9): 
<pre><code>class Post < ActiveRecord::Base
  protected
    def validate
      errors.add_on_empty(["title", "body"])
      errors.add("title", "must be at most 10 characters") if title.size > 10
    end
end
</code></pre>

The "Validation Documentation":http://rails.rubyonrails.com/classes/ActiveRecord/Validations.html has all sorts of details about what methods are available. Also check out the "validation class methods":http://rails.rubyonrails.com/classes/ActiveRecord/Validations/ClassMethods.html available in Rails 0.9.

Note: _validates_confirmation_of_ is very weak.  If the *_confirmation field is nil, the confirmation does not take place.  This makes it easy for poorly written code to by pass the confirmation.

category:Howto
