Rails AR validates_uniqueness_of反对多态关系

aar*_*ell 10 validation activerecord ruby-on-rails polymorphic-associations

是否可以验证子模型的属性与多态关系的唯一性?

例如,我有一个名为field属于的模型fieldable:

class Field < ActiveRecord::Base
  belongs_to :fieldable, :polymorphic => :true
  validates_uniqueness_of :name, :scope => :fieldable_id
end
Run Code Online (Sandbox Code Playgroud)

我还有其他几个有很多字段的模型(Pages,Items).所以我想要的是验证字段名称与父模型的唯一性,但问题是,页面和项目偶尔共享相同的ID号,导致验证失败.

我只是做错了还是有更好的方法来做到这一点?

Ton*_*not 21

只是扩大范围以包括可现场类型:

class Field < ActiveRecord::Base
  belongs_to :fieldable, :polymorphic => :true
  validates_uniqueness_of :name, :scope => [:fieldable_id, :fieldable_type]
end
Run Code Online (Sandbox Code Playgroud)