I'm totally blocked on this.
See this code:
# user.开发者_StackOverflow中文版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
The first test will fail.
The user model validates an associated address model, but is only supposed to do it if a flag is true. In practice it does it all the time.
What is going on?
Actually I ran into further problems with my (more complicated) real world scenario that were only solved by doing the equivalent of:
def validate_associated_records_for_address
self.addressable? ? validate_single_association(User.reflect_on_association(:address)) : nil
end
This adapts anaf's compulsory validations to only run under the condition we want (addressable? is true).
The validates_associated...:if
is not necessary now.
精彩评论