Graham Slick Graham Slick - 6 months ago 9
Ruby Question

Validate uniqueness relatively to the parent

I have a

post
model and a
keyword
model (with a
name
attribute), and a post has_many keywords.
I want to validate the uniqueness of keywords, but relatively to its post, not to all keywords.

What I mean is:
first_post
and
second_post
can both have the keyword
apple
, but they can't have it twice. I'd like to avoid the duplication.

If I just add in the
keyword
model:

validates :name, uniqueness: true


It will check uniqueness of
name
among all the keywords.
How can I precise that it should only be for its post ?

EDIT:
I did add:

validates :name, uniqueness: { scope: post_id }


to the keyword.rb file.
I now get an error:

undefined local variable or method `post_id' for #<Class:0x007f8fa46b7890>


But my keyword model has a post_id attribute. Any idea on what could be causing this ?

Answer

You can use scope.

:scope - One or more columns by which to limit the scope of the uniqueness constraint.

validates :name, uniqueness: { scope: :post_id }
Comments