2

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 ?

Graham Slick
  • 6,692
  • 9
  • 51
  • 87
  • Possible duplicate of [rails 3 validation on uniqueness on multiple attributes](http://stackoverflow.com/questions/3276110/rails-3-validation-on-uniqueness-on-multiple-attributes) – Pavan May 12 '16 at 07:03

1 Answers1

5

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 }
Santhosh
  • 28,097
  • 9
  • 82
  • 87
  • Thanks for your answer. However, I get this error when submitting my form: undefined local variable or method `post_id' for # But my keyword model has a post_id attribute. Any idea on what could be causing this ? – Graham Slick May 12 '16 at 07:13
  • 1
    Sorry my bad. There was a typo in my answer. `post_id` should be a symbol. Fixed it – Santhosh May 12 '16 at 07:53