Last Updated: February 25, 2016
·
3.95K
· kalashnikovisme

Self-referencing association in active record and its factories

Sometime, we need to reference model on itself. In Rails Active Record it seems:

class Member < ActiveRecord::Base
    has_many :children, class_name: "Member",
            foreign_key: "parent_id"

    belongs_to :parent, class_name: "Member"
end

Ok. We need to build factory for this referencing.

FactoryGirl.define do
    factory :member do
        parent      member
    end
end

It doesn't working with such error:

FactoryGirl::AssociationDefinitionError: Self-referencing association 'member' in 'member'

I advise to set parent_id - 1.

FactoryGirl.define do
    factory :member do
        parent_id    1
    end
end

It works and looks good.

2 Responses
Add your response

why not set parent_id to nil, and assoicate them when create new test object? )))

over 1 year ago ·

You may have validates on parent_id not nil.

over 1 year ago ·