Rails idiom to avoid duplicates in has_many :through

前端 未结 8 1848
难免孤独
难免孤独 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

    You can use a combination of validates_uniqueness_of and overriding << in the main model, though this will also catch any other validation errors in the join model.

    validates_uniqueness_of :user_id, :scope => [:role_id]
    
    class User
      has_many :roles, :through => :user_roles do
        def <<(*items)
          super(items) rescue ActiveRecord::RecordInvalid
        end
      end
    end
    

提交回复
热议问题