Search code examples
ruby-on-railsactiverecordassociationshas-and-belongs-to-many

The association `has_and_belongs_to_many` has an option 'uniq'?


I am learning rails with the book 'Rails 4 in Action', and it says the association has_and_belongs_to_many has an option uniq. But it seems it doesn't work as it says. The class below means only unique tags should be retrieved for each ticket, but all the duplicate tags are getting retrieved unlike the book says.

class Ticket < ActiveRecord::Base
  ...
  has_and_belongs_to_many :tags, uniq: true
  ...

Duplicate tags

I now doubt if the association has_and_belongs_to_many has an option uniq. I guess it doesn't have, and I checked this in the active record association document. http://guides.rubyonrails.org/association_basics.html


Solution

  • That should be working:

    has_and_belongs_to_many :tags, -> { uniq }