Forum: Ruby on Rails Validation

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.
775b1c27ba2dcbd4c26438b8a557f0a2?d=identicon&s=25 Bahadır Doğan (xyzt)
on 2007-07-26 13:31
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 ?
4715ae8a9ac5152600ccd3012267ab6b?d=identicon&s=25 James Stewart (Guest)
on 2007-07-29 04:22
(Received via mailing list)
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 Stewart
Play: http://james.anthropiccollective.org
Work: http://jystewart.net/process/
This topic is locked and can not be replied to.