Rails idiom to avoid duplicates in has_many :through

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

    I think you want to do something like:

    user.roles.find_or_create_by(role_id: role.id) # saves association to database
    user.roles.find_or_initialize_by(role_id: role.id) # builds association to be saved later
    

提交回复
热议问题