验证相对于父级的唯一性

Gra*_*ick 2 ruby validation ruby-on-rails

我有一个post模型和一个keyword模型(带有name属性),以及一个帖子 has_many 关键字。我想验证关键字的唯一性,但相对于其帖子,而不是所有关键字。

我的意思是:first_post和second_post都可以有关键字apple,但不能有两次。我想避免重复。

如果我只是添加模型keyword:

validates :name, uniqueness: true
Run Code Online (Sandbox Code Playgroud)

它将检查name所有关键字之间的唯一性。我怎样才能准确地说它应该只用于其帖子?

编辑:我确实添加了:

validates :name, uniqueness: { scope: post_id }
Run Code Online (Sandbox Code Playgroud)

到 keywords.rb 文件。我现在收到一个错误:

undefined local variable or method `post_id' for #<Class:0x007f8fa46b7890>
Run Code Online (Sandbox Code Playgroud)

但我的关键字模型有一个 post_id 属性。知道是什么原因造成的吗?

San*_*osh 5

您可以使用范围。

:scope - 用于限制唯一性约束范围的一列或多列。

validates :name, uniqueness: { scope: :post_id }
Run Code Online (Sandbox Code Playgroud)