为Rails中的自引用关联建立工厂 [英] Build factories for self referential associations in rails

查看:78
本文介绍了为Rails中的自引用关联建立工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个典型的要求,我必须按以下方式处理用户对象

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

现在,我想在Rspec中测试关联.我正在使用工厂女工,所以任何人都可以帮助我建工厂.

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

推荐答案

您需要在此处建立两个工厂,一个工厂用于带有引荐来源的用户,第二个工厂用于不具有引荐来源的用户-否则您将最终陷入无限的创建中环形.您可以为此使用特征:

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)

这篇关于为Rails中的自引用关联建立工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆