Validation


#1

I prepared a form for adding records to the table. I want the model
class to validate the uniqeuness of the name field but it doesn’t give
any errors for the duplicate record.

Here is the controller :

class PetController < ApplicationController
def new
check_authentication
if request.post?
begin
@file = params[:pet_image]
if @file.original_filename.length > 0
pet = Pet.new
#set the fields
pet.save
File.open(filename, “wb”) { |f| f.write(@file.read) }
redirect_to(:controller=>‘user’, :action=>‘petadmin’)
end
end
end
end

def show
check_authentication
end
end

Here is the model :

class Pet < ActiveRecord::Base
belongs_to :user
validates_presence_of :name,:pet_image
validates_uniqueness_of :name, :on => :save, :message => “is already
used.”
end

so, why doesn’t “validates_uniqueness_of” helper work ?


#2

On 26 Jul 2007, at 19:31, Bahadır Doğan wrote:

    begin

end
It looks like you’re not checking whether the model is actually
saving correctly. In the code above, pet.save will return false but
you’re not checking the returned value. You need to either use:

if pet.save
File.open(filename, “wb”) { |f| f.write(@file.read) }
redirect_to(:controller=>‘user’, :action=>‘petadmin’)
else

Fallback action

end

or use pet.save! which will raise an exception if the model is invalid.

You might also want to look at using before_filter rather than
calling check_authentication in every method.

James.


James S.
Play: http://james.anthropiccollective.org
Work: http://jystewart.net/process/