验证Rails中多对多关联的唯一性

Jak*_*old 12 validation activerecord ruby-on-rails

假设我有Project,与Tag有多对多关联.我正在使用has_many,所以我有单独的连接模型.

如何创建验证,检查连接模型的唯一性?现在我只有

has_many :tags, :through => :taggings, :uniq => true
Run Code Online (Sandbox Code Playgroud)

但这不会在保存时验证.

Chr*_*lay 16

我想你想要的是validates_uniqueness_of:

class Taggings
  belongs_to :tags
  validates_uniqueness_of :tag_id, :scope => :project_id
end
Run Code Online (Sandbox Code Playgroud)

这就是我正在使用的,并且效果很好.


Nic*_*k L 5

尝试validates_associated.

我相信,这应该允许在保存之前运行连接模型验证.所以在你的情况下:

class Project
   has many :tags, :through => :taggings
   validates_associated :taggings
end

class Taggings
   belongs_to :tags

   #your validations here....
end

class Tag
   has_many :taggings
end
Run Code Online (Sandbox Code Playgroud)