Using uniq in a has_and_belongs_to_many relationship in Rails 4
activerecord, ruby-on-rails, ruby-on-rails-4
Solution
class User
has_and_belongs_to_many :foos, -> { uniq }
end
According to the documentation here
Problem
I'm trying to implement a unique constraint on a `has_and_belongs_to_many` relationship like so: ``` class User has_and_belongs_to_many :foos, uniq: true end ``` Because I only want unique `foos` when I call `user.foos`, I added the `uniq` option. Since upgrading to Rails 4 I've started to get the following warning: DEPRECATION WARNING: The following options in your User.has_and_belongs_to_many :foos declaration are deprecated: :uniq. Please use a scope block instead. For example, the following: ``` has_many :spam_comments, conditions: { spam: true }, class_name: 'Comment' ``` should be rewritten as the following: ``` has_many :spam_comments, -> { where spam: true }, class_name: 'Comment' ``` I've tried a number of different combinations, and read through the source, but can't figure out how to write the unique constraint to remove the warning?