Take the 2-minute tour ×

I have two models, let's call it model Flower and model Bee. The bees always stick to the same flower, thus they belong_to it. A flower can have multiple Bees, but there's a queen bee, and we want to keep a "pointer" in the flower record that points to the main bee. The reason for this is that we want the flexibility to have flower point to a new bee without requiring modifying the bee model. We also want to avoid having a separate query to locate the right queen bee.

class Flower < ActiveRecord::Base
  belongs_to :queen_bee, class_name: 'Bee'
  has_many :bees

  after_create :create_queen_bee

class Bee < ActiveRecord::Base
  belongs_to :flower

I have a FactoryGirl factory for Flower, and I need to make sure that the queen bee record is created.

What would be right way to do that? The idea is that I should be able to do

flower = FactoryGirl.create(:flower)
puts flower.queen_bee.name
puts flower.queen_bee.flower.name
share|improve this question
add comment

1 Answer

If you're creating it through an after_create callback, then it should automatically be created (given you write create_queen_be properly).

However if you're wanting a way through FactoryGirl, inside your factory you can specify your queen_bee; like so:

factory :flower do
  queen_bee { FactoryGirl.create(:bee) }
share|improve this answer
add comment

Your Answer


