2017-01-11 6 views
0

関連属性を使用して工場出荷時のフィールドを設定します。Railsは私が自己参照関連して、このモデル持って

class Option < ApplicationRecord 
    belongs_to :activity 
    has_many :suboptions, class_name: "Option" 
    belongs_to :parent, class_name: "Option", optional: true 
end 

をそして私はactivity_idが親activity_idに等しいサブオプション工場(FactoryGirlを使用して)作成したいです。どうやってやるの??

おかげで、

答えて

2

あなたは以下のようにafter(:build)after(:create)コールバックを使用することができます。

FactoryGirl.define do 
    factory :option do 
    transient do 
     parent_option nil 
     no_of_suboptions nil 
    end 

    name Faker::Internet.name 
    after(:build) do |option, evaluator| 
     #option.activity_id = evaluator.activity.id 
     if not evaluator.parent_option.blank? 
     #option.parent_id = evaluator.parent_option.id 
     option.parent = evaluator.parent_option 
     end 
    end 

    factory :option_with_suboptions do 
     after(:create) do |option, evaluator| 
     create_list(:option, evaluator.no_of_suboptions, :activity => option.activity, :parent => option) 
     end 
    end 
    end 
end 

使用

FactoryGirl.create(:option_with_suboptions, :activity => activity, :no_of_suboptions => 5)

一つはactivityオブジェクトが存在することを確認する必要があります。一つは、あなたのGemfileにfaker宝石を追加Gemfileno_of_suboptions

を使用して作成することが

suboptionsの数を設定することができます。

group :development, :test do 
    gem 'faker' 
end 
+0

これは「name Faker :: Internet.name'」とは何ですか? –

+0

申し訳ありません。 'Faker :: Internet.name'はあなたのために偽のデータを生成します。 gemfileにgem 'faker'を追加して' bundle'を実行することができます。 – fossil

関連する問題