Topic: validates_uniqueness_of ONLY if a value is entered

Hi,

I'm using RoR with PostgreSQL (and I'm beginner with ruby and rails).

In a model I would like to "validates_uniqueness_of" of a field if not blank.
In other words, I have a field named "truc" who can either be blanc or "" either be unique.

It was adviced to me to to :
validates_uniqueness_of :truc :if => Proc.new { |truc| not truc.nil? }

but it don't work...

So truc is a field of my table named person and has to be unique or blank

Many thanks for help

Re: validates_uniqueness_of ONLY if a value is entered

validates_uniqueness_of :username, :if => username_required?

  def username_required?
    !username.blank?
  end


Something like that?

Re: validates_uniqueness_of ONLY if a value is entered

yes something like


###
# in the model

validates_uniqueness_of :truc, :if => truc_defined?, :message => "This truc already exists !"
   
###
# Somewhere in the model
def truc_defined?
  ! self.truc.blank?
  # ! truc.blank?
end

# end of the model
###

but the working version...

undefined local variable or method `truc_defined?' for Client:Class

Many thanks

Re: validates_uniqueness_of ONLY if a value is entered

#Model.rb
validates_uniqueness_of :truc, :if => :truc_defined?, :message => "This truc already exists !"
def truc_defined?
!truc.blank?
end

That should work.

Edit: I fixed the typo, just paste that code and you should be good to go.
Another typo, thanks ryanb.

Last edited by zingzong (2007-02-02 12:45:10)

Re: validates_uniqueness_of ONLY if a value is entered

don't forget the colon in front of "truc_defined?" to make it a symbol.

validates_uniqueness_of :truc, :if => :truc_defined?, :message => "This truc already exists !"

Railscasts - Free Ruby on Rails Screencasts