1
我完全被封鎖了。validates_associated not honoring:if
看到這個代碼:
# user.rb
class User < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
validates_associated :address, :if => Proc.new {|u| u.addressable? }
end
# address.rb
class Address < ActiveRecord::Base
belongs_to :user
validates_presence_of :address_text
end
# user_test.rb
require File.dirname(__FILE__) + '/../test_helper'
class UserTest < ActiveSupport::TestCase
setup { }
test "address validation is not ran w update attributes and anaf" do
@user = User.create!
@user.build_address
assert_nothing_raised do
@user.update_attributes!(:addressable => false, :address_attributes => {:address => "test"})
end
end
test "address validation w update_attributes and anaf" do
@user = User.create!
@user.build_address
@user.save
assert_raise ActiveRecord::RecordInvalid do
@user.update_attributes!(:addressable => true, :address_attributes => {:address => "test"})
end
end
end
的第一個測試將失敗。
用戶模型驗證關聯的地址模型,但只應該這樣做如果標誌爲真。在實踐中,它一直都在這樣做。
這是怎麼回事?