shiran
February 18, 2010, 11:40am
1
Hi,
I need to use validates_uniqueness_of only when inserting new records
but not when update them.
I use the following line of code,
validates_uniqueness_of :type_id, :scope => [:user_name], :unless
=> :update, :message => “This has already been registered”
But still it doesn’t run validations and allow duplicate inserts.
Thanks in advance for your feedback.
BR,
Shiran
shiran
February 18, 2010, 11:42am
2
On Feb 18, 10:32 am, shiran [email protected] wrote:
But still it doesn’t run validations and allow duplicate inserts.
Looks like you’re confusing the :unless/:if options (which take a
method name or block and run the validation depending on whether the
block/method evaluates to true) and the :on option.
Fred
shiran
February 18, 2010, 11:53am
3
Thanks Fred… will look at it
On Feb 18, 3:40 pm, Frederick C. [email protected]
shiran
February 18, 2010, 11:45am
4
validates_uniqueness_of :type_id, :scope => [:user_name], :message =>
“This has already been registered”, :if => :new_record?
shiran
February 18, 2010, 11:55am
5
Hi,
As you need to fire uniqueness validation during creation of new
record.
validates_uniqueness_of :type_id, :scope => [:user_name],:on =>
:create, :message => “This has already been registered”
shiran
February 18, 2010, 4:43pm
8
Another technique which may be overkill for what you need is doing
something
like this…
Say you have a very simple user signup but, after signup they have to
fill
in a more extensive user profile which has many more fields. I’ve
solved
this by doing:
class User < ActiveRecord::Base
validates_presence_of :login, :email
validates_presence_of :password, :unless => :password_set
validates_presence_of :password_confirm, :unless => :password_set
validates_length_of :password, :within => 4…40, :unless =>
:password_set
validates_confirmation_of :password, :unless => :password_set
validates_length_of :login, :within => 3…40
validates_length_of :email, :within => 3…100
validates_uniqueness_of :login, :email, :case_sensitive => false
validates_as_email :email
end
This handles the User Form validations
class UserForm < User
validates_presence_of :first_name
validates_presence_of :last_name
end
When doing things that require first, last name just use the UserForm
object
instead.