# Validation

**URL:** <https://www.ruby-forum.com/t/validation/110450>\
**Category:** Rails\
**Created:** [July 26, 2007, 1:31pm UTC](https://www.ruby-forum.com/t/validation/110450 "2007-07-26T13:31:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![xyzt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/839c29/32.png) [@xyzt](https://www.ruby-forum.com/u/xyzt)\
**Post date:** [July 26, 2007, 1:31pm UTC](https://www.ruby-forum.com/t/validation/110450/1 "2007-07-26T13:31:45Z")

</div>

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 ?

---

<div class="post-metadata">

**Author:** ![xyzt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/839c29/32.png) [@xyzt](https://www.ruby-forum.com/u/xyzt)\
**Post date:** [July 29, 2007, 4:22am UTC](https://www.ruby-forum.com/t/validation/110450/2 "2007-07-29T04:22:34Z")

</div>

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](http://james.anthropiccollective.org)  
Work: [Processing Greenbelt 2009 – James Stewart](http://jystewart.net/process/)
