2010-06-03 19 views
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 

的第一個測試將失敗。

用戶模型驗證關聯的地址模型,但只應該這樣做如果標誌爲真。在實踐中,它一直都在這樣做。

這是怎麼回事?

回答

1

其實我碰到了我的(更復雜的)真實的場景進一步的問題,只通過做相當於解決:

def validate_associated_records_for_address 
    self.addressable? ? validate_single_association(User.reflect_on_association(:address)) : nil 
end 

這適應ANAF的強制驗證只有我們想要的狀態下運行(可尋址?是真實的)。

現在不需要validates_associated...:if