我的代码中有以下关联(简化):
class Department < ActiveRecord::Base
has_many :organisational_structures, :as => :structurable, :dependent => :destroy
accepts_nested_attributes_for :organisational_structures, :allow_destroy => true
end
class OrganisationalStructure < ActiveRecord::Base
belongs_to :structurable, polymorphic: true
validates_uniqueness_of :department, :scope => [:faculty, :institute, :structurable], if: proc { |og| og.structurable.class != Department }
end
我认为验证失败,因为Department
在验证OrganisationalStructure
时未创建/保存。如果关联不是多态的,则将:inverse_of
关键字提供给has_many
和belongs_to
关联将解决问题,但这不适用于多态关联。
我尝试创建新Department
时出现的错误:
NoMethodError (undefined method `attributes' for nil:NilClass):
activerecord (4.0.2) lib/active_record/validations/uniqueness.rb:56:in `build_relation'
activerecord (4.0.2) lib/active_record/validations/uniqueness.rb:22:in `validate_each'
globalize (4.0.1) lib/patches/active_record/uniqueness_validator.rb:35:in `validate_each_with_translations'
activemodel (4.0.2) lib/active_model/validator.rb:153:in `block in validate'
activemodel (4.0.2) lib/active_model/validator.rb:150:in `each'
activemodel (4.0.2) lib/active_model/validator.rb:150:in `validate'
activesupport (4.0.2) lib/active_support/callbacks.rb:283:in `_callback_before_430'
...
我的问题:是否有标准的Rails方法为这种情况创建验证?