Build factories for self referential associations in rails

戏子无情 提交于 2019-12-23 04:13:11

问题


I have a typical requirement, I have to address user object as follows

user.referrer and user.referrers.

Basically, user can refer more than one person and one person should be referred by one particular user. So I build associations as follows. They are working great.

class User < ActiveRecord::Base
    attr_accessible :account_number, :display_name, :referrer_id

    has_many :referrers, :class_name => "User", :foreign_key => "referrer_id"
    belongs_to :referrer, :class_name => "User"
end

Now I would like to test assoications in Rspec. I am using factory girl so any one help me to build factories.

I tried as follows but end up with an errors

factory :user do
  gender :male
  name "super test"
  .....
  .....

  factory :referrer do
  end
  association :referrer
end

回答1:


You need to build two factories here, one for user with a referrer and second one for user without a referer - otherwise you'll end up in the infinite creation loop. You might use traits for this:

factory :user do
  gender :male
  name "super test"

  trait :with_referrer do
    association :referrer, factory: :user
  end
end

FactoryGirl.create(:user, :with_referrer)


来源:https://stackoverflow.com/questions/35940681/build-factories-for-self-referential-associations-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!