Rails has_many and belongs_to on same model

144 Views Asked by At

I have a School model that has_many :users. But, each school also has a primary_user. Here is my model:

 has_many :users
 belongs_to :primarycontact, :class_name => "User"

This works fine in my my production and dev app, but it raises stack level errors in FactoryGirl while testing. The associations smell bad to me, and the stack level errors in testing indicate to me that there is probably a better way.

Is there a better way? ...any ideas why FactoryGirl is struggling with it?

my factory

  FactoryGirl.define do
    factory :school do
      name "Test School"
      association :primarycontact, factory: :user, name: "Primary User"
    end
  end

Stack trace

  Userdoc
    test_0001_must be valid 0:00:09.143 ERROR
      stack level too deep
      Exception `SystemStackError' at:

So, the error is originating in a third model, Userdoc. When the factory creates a Userdoc, it creates a User, .. the user must belong to a school so that factory also creates a School. But, when the school factory gets triggered it also tries to create a user because of the primarycontact association.

0

There are 0 best solutions below