Bug in validates_associated?


#1

Here is the setup:

Windows XP, InstantRails, MySQL 14.7, Ruby 1.8.4, Rails 1.1.2

MODEL:

class Office<ActiveRecord::Base
has_many :users
end

class User<ActiveRecord::Base
belongs_to :office

validates_presence_of :office_id
validates_associated :office

<…other stuff…>
end

UNIT_TEST test/unit/user_test.rb

def test_associations
u = User.new
u.office_id = 2222 # Invalid office id
assert !u.save # Expected because of the invalid office id

u.office_id = 2    # Valid office ID, found in fixtures
assert u.save      # This works! So far, so good

u.office_id = 2222
assert !u.save     # THIS SHOULD FAIL, BUT DOES NOT

end

Can someone explain this behavior?

thanks


#2

Dhritiman Banerjee wrote:

<…other stuff…>
assert u.save # This works! So far, so good

u.office_id = 2222
assert !u.save     # THIS SHOULD FAIL, BUT DOES NOT

end

Can someone explain this behavior?

You probably want to replace the two validation statements you’re
using with:
validates_presence_of :office

The office attribute will be nil when office_id is not set to the
id of an existing office record, but validates_associated will
pass because there’s no associated object to check.


We develop, watch us RoR, in numbers too big to ignore.