Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate uniqueness of many to many association in Rails

Say I have Project, that is in many-to-many association with Tag. I'm using has_many through so I have separate join model.

How do I create validation, that checks uniqueness of join model? Now I have only

has_many :tags, :through => :taggings, :uniq => true

But that doesn't validate on save.

like image 810
Jakub Arnold Avatar asked Sep 14 '09 13:09

Jakub Arnold


2 Answers

Try validates_associated.

That should, I believe, allow the join model validations to run before saving. So in your case:

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
like image 156
Nick L Avatar answered Nov 15 '22 18:11

Nick L


I think what you want is validates_uniqueness_of:

class Taggings
  belongs_to :tags
  validates_uniqueness_of :tag_id, :scope => :project_id
end

This is what I'm using, and works well.

like image 35
Christopher Pickslay Avatar answered Nov 15 '22 19:11

Christopher Pickslay