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.
Written by Павел Калашников
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#