Rails idiom to avoid duplicates in has_many :through

前端 未结 8 1856
难免孤独
难免孤独 2020-12-07 12:09

I have a standard many-to-many relationship between users and roles in my Rails app:

class User < ActiveRecord::Base
  has_many :user_roles
  has_many :ro         


        
8条回答
  •  青春惊慌失措
    2020-12-07 13:00

    As long as the appended role is an ActiveRecord object, what you are doing:

    user.roles << role
    

    Should de-duplicate automatically for :has_many associations.

    For has_many :through, try:

    class User
      has_many :roles, :through => :user_roles do
        def <<(new_item)
          super( Array(new_item) - proxy_association.owner.roles )
        end
      end
    end
    

    if super doesn't work, you may need to set up an alias_method_chain.

提交回复
热议问题