How to create has_and_belongs_to_many associations in Factory girl

前端 未结 11 626
生来不讨喜
生来不讨喜 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:48

    I couldn´t find an example for the above mentioned case on the provided website. (Only 1:N and polymorphic assocations, but no habtm). I had a similar case and my code looks like this:

    Factory.define :user do |user|
     user.name "Foo Bar"
     user.after_create { |u| Factory(:company, :users => [u]) }
    end
    
    Factory.define :company do |c|
     c.name "Acme"
    end
    

提交回复
热议问题