Validates_uniqueness_of problem

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:ineach’
/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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs