Topic: Form validation with Rails

Alright, so I have everything going smoothly, running Rails 1.2 and everything is fine.

I get to the validation section of "Agile web development with rails"... and put this in my model class...

class Product < ActiveRecord::Base
    validates_presence_of :title, :description, :image_url
end

ANd thats it.. I use scaffold on the controller... nothing wrong with it, just for some simplistic testing..

However, the validation does not work.. it does not give any errors or anything, it does enter it into the database however.. which is not what I want.. I have followed the book exactly though sad

Any know why its not working?

Re: Form validation with Rails

Can you paste the code that is in the controller which creates the Product model?

Railscasts - Free Ruby on Rails Screencasts

Re: Form validation with Rails

Its as simplistic as it gets lol..

class AdminController < ApplicationController
  scaffold :product
end

Thats it! yikes

Re: Form validation with Rails

I have the same book and I think I'm on the same part as you.

My admin_controller is as follows:

class AdminController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @product_pages, @products = paginate :products, :per_page => 10
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(params[:product])
    if @product.save
      flash[:notice] = 'Product was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @product = Product.find(params[:id])
  end

  def update
    @product = Product.find(params[:id])
    if @product.update_attributes(params[:product])
      flash[:notice] = 'Product was successfully updated.'
      redirect_to :action => 'show', :id => @product
    else
      render :action => 'edit'
    end
  end

  def destroy
    Product.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end


Here's my product.rb:
class Product < ActiveRecord::Base
    # Test to make sure the text fields aren't empty
    validates_presence_of :title, :description, :image_url
    # Make sure price is a number
    validates_numericality_of :price
    # Make sure no other row in products has the same title
    validates_uniqueness_of :title
    # Validate URL
    validates_format_of :image_url,
        :with    => %r{^http:.+\.(gif|jpg|png)$}i,
        :message => "must be URL for a GIF, JPG, or PNG image"
       
    protected
        def validate
            errors.add(:price, "should be positive") unless price.nil? || price > 0.0
        end
   
   
end

It all works...