Forum: Ruby on Rails Bug in validates_associated?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dhritiman Banerjee (Guest)
on 2006-04-27 02:45
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
Mark Reginald J. (Guest)
on 2006-04-27 05:40
(Received via mailing list)
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.
This topic is locked and can not be replied to.