多态关联的验证

时间:2014-05-29 13:42:49

标签: ruby-on-rails validation polymorphic-associations

我的代码中有以下关联(简化):

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_manybelongs_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方法为这种情况创建验证?

0 个答案:

没有答案