Forum: Ruby on Rails Does not validate presence of entry fields

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Pepe S. (Guest)
on 2008-10-14 04:01
Hi all

I wrote a small form and I am trying to check if the fields are
populated.

My Model is:
class Contact < ActiveRecord::Base
   validates_presence_of :name,  :email, :body
  validates_length_of :body, :maximum =>2000
end

-----Controller
class ContactController < ApplicationController
  def new
      @contact = Contact.new
   end
  def create
    @contact = Contact.new(params[:contact])
   @contact.save
  end
end

------Viewers

New view

<%= error_messages_for :contact %>

<% form_for @contact, :url => { :action => 'create' }, :html => {
:method => :post }  do |f| %>
<fieldset>
<legend>Please send your message: </legend>
<p><label>Your N.:<br /><%= f.text_field :name, :size => 25
%></label></p>
<p><label>Your email:<br /> <%= f.text_field :email, :size => 25
%></label></p>
<p><label>Message:<br /><%= f.text_area :body, :rows => 10, :cols => 30
%></label></p>
<p><label><%= submit_tag 'Submit'   %> </label></p>
</fieldset>
<% end %>


Create view
<h2>Thank you for your interest in my site</h2>




When the entry fields are not populated the forms shows the create view
and does not show any error message. why?

thanks
Philip H. (Guest)
on 2008-10-14 06:08
(Received via mailing list)
>
>
> <p><label>Your N.:<br /><%= f.text_field :name, :size => 25
>
> Create view
> <h2>Thank you for your interest in my site</h2>
>
>
>
>
> When the entry fields are not populated the forms shows the create
> view
> and does not show any error message. why?

Because you aren't doing anything in the create action to adjust the
result if there is a failure.  You want something more like this:

def create
   @contact = Contact.new(params[:contact])
   unless @contact.save
     render :action => 'new'
     return
   end
end

Or this which is pretty close to the default generated by Rails
scaffolding.

   def create
     @contact = Contact.new(params[:contact])

     if @contact.save
       flash[:notice] = 'Contact was successfully created.'
       redirect_to(contact_path(@contact))
     else
       render :action => "new"
     end
   end
Pepe S. (Guest)
on 2008-10-15 05:33
thanks!!!
This topic is locked and can not be replied to.