Topic: HABTM or has_many :through and uniqueness?

Hi guys,

I've been using a "has_and_belongs_to_many" relationship to assign categories to items in my database. It's working great but it's quite easy to mistakenly add a category to the same item twice.

So the question is this: Is there a method similar to "validates_uniqueness_of" that will check for duplicate HABTM associations?

-- Marsvin

Re: HABTM or has_many :through and uniqueness?

Not sure how well this will work, and I'm sure there's a better way, but try this:

# in item.rb
def validate
  errors.add_to_base('category has already been added to this item') if categories.size > categories.uniq.size
end

Railscasts - Free Ruby on Rails Screencasts

Re: HABTM or has_many :through and uniqueness?

That looks pretty good..

I'm thinking maybe you could even reverse that and put it in a before filter type thing.. Do you think this would work?

# item.rb
before_save :remove_dupes

def remove_dupes
  self.categories = self.categories.uniq
end

Last edited by marsvin (2006-11-25 18:52:52)

Re: HABTM or has_many :through and uniqueness?

Yeah, that will work too. Neither solution is that efficient, but it gets the job done.

Railscasts - Free Ruby on Rails Screencasts