How to create has_and_belongs_to_many associations in Factory girl

前端 未结 11 669
生来不讨喜
生来不讨喜 2020-12-07 09:27

Given the following

class User < ActiveRecord::Base
  has_and_belongs_to_many :companies
end

class Company < ActiveRecord::Base
  has_and_belongs_to_m         


        
11条回答
  •  孤街浪徒
    2020-12-07 09:56

    First of all I strongly encourage you to use has_many :through instead of habtm (more about this here), so you'll end up with something like:

    Employment belongs_to :users
    Employment belongs_to :companies
    
    User has_many :employments
    User has_many :companies, :through => :employments 
    
    Company has_many :employments
    Company has_many :users, :through => :employments
    

    After this you'll have has_many association on both sides and can assign to them in factory_girl in the way you did it.

提交回复
热议问题