Rails idiom to avoid duplicates in has_many :through

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

    Use Array's |= Join Method.

    You can use Array's |= join method to add an element to the Array, unless it is already present. Just make sure you wrap the element in an Array.

    role                  #=> #
    
    user.roles            #=> []
    
    user.roles |= [role]  #=> [#]
    
    user.roles |= [role]  #=> [#]
    

    Can also be used for adding multiple elements that may or may not already be present:

    role1                         #=> #
    role2                         #=> #
    
    user.roles                    #=> [#]
    
    user.roles |= [role1, role2]  #=> [#, #]
    
    user.roles |= [role1, role2]  #=> [#, #]
    

    Found this technique on this StackOverflow answer.

提交回复
热议问题