# Validates\_uniqueness\_of problem

**URL:** <https://www.ruby-forum.com/t/validates-uniqueness-of-problem/195344>\
**Category:** Rails\
**Created:** [September 21, 2010, 11:36pm UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-problem/195344 "2010-09-21T23:36:10Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![giorgio](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/cab0a1/32.png) [@giorgio](https://www.ruby-forum.com/u/giorgio)\
**Post date:** [September 21, 2010, 11:36pm UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-problem/195344/1 "2010-09-21T23:36:10Z")

</div>

I have an after\_save callback when I save an Organisation record.

def after\_save  
#create an admin user for this organisation  
if self.users.size.zero?  
user=User.new(:organisation\_id=\>self.id,  
:first\_name =\> “Admin”,  
:last\_name =\> “User”,  
:logon\_name =\> “admin”,  
:password =\> “secret\_password”,  
:privilege\_bits =\> 3,  
:active =\> 1 )  
user.save  
end  
end

The User table has “validate\_uniqueness\_of” which appears to create a  
problem.

class User \< BaseServiceTable  
before\_validation\_on\_create :set\_initial\_password  
serialize :permitted\_programmes , Array

attr\_accessor :password\_confirmation

validates\_presence\_of :logon\_name  
validates\_uniqueness\_of :logon\_name, :scope =\> :organisation\_id  
…

Here is the sql from te dev log:  
SQL (0.1ms) BEGIN  
Organisation Exists (0.3ms) SELECT `organisations`.id FROM  
`organisations` WHERE (`organisations`.`logon_name` = BINARY ‘abcd’)  
LIMIT 1  
Organisation Create (0.3ms) INSERT INTO `organisations` (`name`,  
`logon_name`, `password`, `active`) VALUES(‘ABcd Org’, ‘abcd’,  
‘OrgPassword’, 1)  
SQL (0.4ms) SELECT count(\*) AS count\_all FROM `users` WHERE  
(`users`.organisation\_id = 12)  
SQL (53.2ms) ROLLBACK

Here is (top of) the stack trace:  
NoMethodError (You have a nil object when you didn’t expect it!  
The error occurred while evaluating nil.columns\_hash):  
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active\_record/  
validations.rb:723:in `validates_uniqueness_of' /usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/ validations.rb:400 /usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/ validations.rb:397:in`each’  
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active\_record/  
validations.rb:397

I have had a look at the validation code and not sure what the problem  
is. Not sure if it is because User inherits from an abstract table?

I am tempted just to do the validation manually as I dont have time  
for lengthy messing around, but I just wondered if anyone had seen the  
same problem?

Cheers  
George
