我有一个post
模型和一个keyword
模型(带有name
属性),还有一个帖子has_many关键字。
我想验证关键字的唯一性,但相对于其帖子,而不是所有关键字。
我的意思是:first_post
和second_post
都可以使用关键字apple
,但是它们不能有两次。我想避免重复。
如果我只是添加keyword
模型:
validates :name, uniqueness: true
它会检查所有关键字中name
的唯一性。
我怎样才能确定它应该只用于它的帖子?
编辑: 我添加了:
validates :name, uniqueness: { scope: post_id }
到keyword.rb文件。 我现在收到一个错误:
undefined local variable or method `post_id' for #<Class:0x007f8fa46b7890>
但我的关键字模型有一个post_id属性。有什么可能导致这个的想法吗?
答案 0 :(得分:3)
您可以使用范围。
:scope - 用于限制范围的一个或多个列 唯一性约束。
_.findWhere(fruits, {title: 'Apple'});