Avoiding adding duplicates to has_many collection?

Since there’s no ‘exists?’ method for a has_many collection, is there an
easier way to avoid adding duplicates to a collection? (I assume
obj.items << item would add duplicates if repeatedly called.) Right now
I do:

category = Category.find_or_create_by_name(category_name)

directory.categories << [ category ] if
directory.categories.find(:first, :conditions=>[‘category_id=?’,
category.id]).nil?

YUCK. Sure would be nice if there was a ‘collection#exists?(id)’ or
‘collection#exists?(obj)’.

Joe

Ruby’s include? seems to do the trick.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs