validates_associated不尊重:如果

时间:2010-06-03 05:54:11

标签: ruby-on-rails ruby conditional

我完全被封锁了。

请参阅此代码:

# 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 个答案:

答案 0 :(得分:1)

实际上我遇到了更复杂的现实世界场景的问题,这些问题只能通过以下方式解决:

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

这使得anaf的强制性验证只能在我们想要的条件下运行(可寻址?是真的)。​​

现在不需要validates_associated...:if